加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

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

发布时间:2020-12-12 06:14:40 所属栏目:MsSql教程 来源:网络整理
导读:我设置了这个奇怪行为的小例子 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 @tm
我设置了这个奇怪行为的小例子
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还必须将游标类型从动态更改为静态.这没有特别好记录,但您可以很容易地看到行为.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读