Cio*_*Ion 2 sql t-sql database sql-server
我已经设置了这个奇怪行为的小例子
SET NOCOUNT ON;
create table #tmp
(id int identity (1,1),
value int);
insert into #tmp (value) values(10);
insert into #tmp (value) values(20);
insert into #tmp (value) values(30);
select * from #tmp;
declare @tmp_id int, @tmp_value int;
declare tmpCursor cursor for
select t.id, t.value from #tmp t
--order by t.id;
open tmpCursor;
fetch next from tmpCursor into @tmp_id, @tmp_value;
while @@FETCH_STATUS = 0
begin
print 'ID: '+cast(@tmp_id as nvarchar(max));
if (@tmp_id = 1 or @tmp_id = 2)
insert into #tmp (value)
values(@tmp_value * 10);
fetch next from tmpCursor into @tmp_id, @tmp_value;
end
close tmpCursor;
deallocate tmpCursor;
select * from #tmp;
drop table #tmp;
Run Code Online (Sandbox Code Playgroud)
我们可以print
在游标如何解析#tmp
表中的新行的帮助下观察.但是,如果我们order by t.id
在游标声明中取消注释- 则不会解析新行.
这是预期的行为吗?
你看到的行为相当微妙.默认情况下,SQL Server中的游标是动态的,因此您可能会看到更改.但是,埋在文档中的是这一行:
如果select_statement中的子句与请求的游标类型的功能冲突,则SQL Server会将游标隐式转换为另一种类型.
当您包含时order by
,SQL Server会读取所有数据并将其转换为临时表进行排序.在此过程中,SQL Server还必须将游标类型从动态更改为静态.这没有特别好记录,但你可以很容易地看到这种行为.
您可以使用sp_describe_cursor存储过程来查看游标的元数据.在您的示例中这样做会显示以下内容:
ORDER BY包括:
model =不敏感(或静态),并发 =只读
ORDER BY排除:
model =动态,并发 =乐观
来源:http://technet.microsoft.com/en-us/library/ms173806(v = sql.105).aspx