Cursor - Declare Select-语句执行多次?

Cursor - Declare Select-Statement executed multiple times?

我有一个关于 t-sql 中的游标的问题。 当我做这样的游标时,它会陷入无限循环。

drop table  [dbo].[cursorcheck]
GO

CREATE TABLE [dbo].[cursorcheck](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Wert] [varchar](10) NOT NULL
) ON [PRIMARY]
GO


delete dbo.cursorcheck
GO

insert into dbo.cursorcheck 
select 'Insert'
GO


DECLARE @vendor_id int, @vendor_name nvarchar(50);

DECLARE vendor_cursor CURSOR FOR 

SELECT ID, wert
FROM dbo.cursorcheck 
WHERE wert = 'insert';

OPEN vendor_cursor

FETCH NEXT FROM vendor_cursor 
INTO @vendor_id, @vendor_name

WHILE @@FETCH_STATUS = 0
BEGIN



        insert into dbo.cursorcheck 
        select 'Insert'


    FETCH NEXT FROM vendor_cursor 
    INTO @vendor_id, @vendor_name
END 
CLOSE vendor_cursor;
DEALLOCATE vendor_cursor;

我对这种行为有点困惑。这是否意味着声明游标的 select 脚本执行了多次?当我在调试游标时从另一个事务插入 table 时,我得到了同样的效果。当我使用 "static" 关键字声明游标时,问题就解决了。但是当我不使用 static 关键字时,我对光标的行为感到困惑。

有什么解释吗?

此致, 雷托

关键是你尝试在循环中读取并插入相同的 table(所以它就像 "a snake eating own tail"):

光标:

DECLARE vendor_cursor CURSOR FOR 
  SELECT ID, wert
  FROM dbo.cursorcheck 
  WHERE wert = 'insert';

然后循环:

WHILE @@FETCH_STATUS = 0
BEGIN
    insert into dbo.cursorcheck 
    select 'Insert'

    FETCH NEXT FROM vendor_cursor 
    INTO @vendor_id, @vendor_name
END 

第二个问题:当我使用"static"时问题解决了:

STATIC CURSOR

The complete result set of a static cursor is built in tempdb when the cursor is opened. A static cursor always displays the result set as it was when the cursor was opened.

和:

The cursor does not reflect any changes made in the database that affect either the membership of the result set or changes to the values in the columns of the rows that make up the result set. A static cursor does not display new rows inserted in the database after the cursor was opened, even if they match the search conditions of the cursor SELECT statement