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

前端之家收集整理的这篇文章主要介绍了sql – 为什么为具有ORDER by的选项打开游标不会反映对后续表的更新前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我设置了这个奇怪行为的小例子
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;

我们可以在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还必须将游标类型从动态更改为静态.这没有特别好记录,但您可以很容易地看到行为.

原文链接:https://www.f2er.com/mssql/79840.html

猜你在找的MsSQL相关文章