2

私は奇妙な行動のこの小さな例を設定しました

    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ます。order by t.idただし、カーソル宣言でコメントを外すと、新しい行は解析されません。

これは意図した動作ですか?

4

3 に答える 3

5

sp_describe_cursor ストアド プロシージャを使用して、カーソルのメタデータを表示できます。あなたの例でそうすると、次のことがわかります。

ORDER BY が含まれています:

モデル= インセンシティブ (または静的)、並行性= 読み取り専用

ORDER BY を除外:

モデル= 動的、並行性= 楽観的

ソース: http://technet.microsoft.com/en-us/library/ms173806(v=sql.105).aspx

于 2013-01-05T14:36:49.457 に答える
5

The behavior you see is rather subtle. By default, cursors in SQL Server are dynamic, so you would expect to see changes. However, buried in the documentation is this line:

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

When you include the order by, SQL Server reads all the data and turns it into a temporary table for sorting. In this process, SQL Server must also change the type of cursor from dynamic to static. This is not particularly well documented, but you can readily see the behavior.

于 2013-01-05T14:22:31.310 に答える
2

I think that by putting in an ORDER BY clause it then forces the CURSOR to be a STATIC CURSOR whereas without it defaults to DYNAMIC.

于 2013-01-05T14:22:02.127 に答える