【问题标题】:cursor fetch statement calling first row repetedly游标获取语句重复调用第一行
【发布时间】:2017-05-11 20:34:11
【问题描述】:

你好,

我用只有 10 行的简单选择语句创建了一个游标 当我要在 @@fetch_status=0 之后打印时,它会递归 只调用第一行,执行没有停止。 我不知道为什么只显示第一行重复光标不会移动到第二行

  Here below is my code

  declare cur_data  cursor for

 select DISTINCT pkd.boxnumber  from packagedetail pkd
 inner join PalletDetail pld on pld.boxnumber=pkd.boxnumber
 INNER JOIN TRACKING T ON T.BOXNUM=PKD.SCANBOXID
 where pkd.shipmentlocation='NYWH' AND pld.shipmentnumber='SH0675535'

 declare @boxnumber NVARCHAR(50)

 open cur_data 

 fetch next from cur_data  into @boxnumber
 while @@fetch_status=0
 begin

 print @boxnumber

END
close cur_data
deallocate cur_data

【问题讨论】:

  • 你必须在你的 while 循环中重新获取,否则你永远不会得到下一行
  • 游标被大多数人广泛鄙视,因为它们非常低效——它们有它们的用途,但它们之间的距离很少……你可能最好在这里使用不同的方法,这取决于你需要做什么。

标签: sql sql-server-2008 cursor


【解决方案1】:

你必须有一个 fetch ... next 在你的 while 循环中...

 ...
 open cur_data 
 fetch next from cur_data  into @boxnumber
 while @@fetch_status=0
 BEGIN
     print @boxnumber
     fetch next from cur_data  into @boxnumber
 END
 ...

【讨论】:

  • 当您运行您的选择语句时,您的查询返回了多少行?你的光标语法似乎没问题...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 2012-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多