sql – 为什么为具有ORDER by的选项打开游标不会反映对后续表的更新

前端之家收集整理的这篇文章主要介绍了sql – 为什么为具有ORDER by的选项打开游标不会反映对后续表的更新前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我设置了这个奇怪行为的小例子
  1. SET NOCOUNT ON;
  2. create table #tmp
  3. (id int identity (1,1),value int);
  4.  
  5. insert into #tmp (value) values(10);
  6. insert into #tmp (value) values(20);
  7. insert into #tmp (value) values(30);
  8.  
  9. select * from #tmp;
  10.  
  11. declare @tmp_id int,@tmp_value int;
  12. declare tmpCursor cursor for
  13. select t.id,t.value from #tmp t
  14. --order by t.id;
  15.  
  16. open tmpCursor;
  17.  
  18. fetch next from tmpCursor into @tmp_id,@tmp_value;
  19.  
  20. while @@FETCH_STATUS = 0
  21. begin
  22. print 'ID: '+cast(@tmp_id as nvarchar(max));
  23.  
  24. if (@tmp_id = 1 or @tmp_id = 2)
  25. insert into #tmp (value)
  26. values(@tmp_value * 10);
  27.  
  28. fetch next from tmpCursor into @tmp_id,@tmp_value;
  29. end
  30.  
  31. close tmpCursor;
  32. deallocate tmpCursor;
  33.  
  34. select * from #tmp;
  35. drop table #tmp;

我们可以在print的帮助下观察游标如何解析#tmp表中的新行.但是,如果我们在游标声明中通过t.id取消注释顺序 – 则不会解析新行.

这是预期的行为吗?

解决方法

你看到的行为相当微妙.默认情况下,sql Server中的游标是动态的,因此您可能会看到更改.然而,埋在 documentation是这一行:

sql Server implicitly converts the cursor to another type if clauses
in select_statement conflict with the functionality of the requested
cursor type.

当您包含订单时,sql Server会读取所有数据并将其转换为临时表进行排序.在此过程中,sql Server还必须将游标类型从动态更改为静态.这没有特别好记录,但您可以很容易地看到行为.

猜你在找的MsSQL相关文章