从游标源 SQL Server 中删除行

发布于 2024-12-08 16:41:15 字数 384 浏览 0 评论 0原文

我有一个 SQL Server 2005 游标,对一个名为 @workingSet 的表变量进行操作。

有时行可能是相关的,在这种情况下,我同时处理已获取的行和相关行。然后,我从 @workingset 中删除相关记录,因为我不需要在循环中进行处理。

在具有 7 行的 @workingSet 中,前两行是相关的,因此当我处理 1 时,我也会处理 2。我从游标源 (@workingSet) 中删除第 2 行,并且然后获取下一个。问题是它返回 @workingset 中的第二行(我在上一次迭代中删除的行)。

我的印象是,这可以完成,即从游标操作的源中删除一个项目,并且它将在后续的提取中遵循删除操作。

I have a SQL Server 2005 cursor operating over a table variable called @workingSet.

Some times rows can be related and in this case I process the row I have fetched and the related rows at the same time. I then remove the related records from @workingset as I don't need to process then in the loop.

In a @workingSet with 7 rows, the first two are related so when I process 1 I also process 2. I remove row 2 from the cursor source (@workingSet) and then fetch next. The problem is it returns the second row in @workingset (the one I deleted on the previous iteration).

I was of the impression that this could be done i.e. deleting an item from a source that a cursor operates on and it will honour the delete in subsequent fetches.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风向决定发型 2024-12-15 16:41:15

答案似乎是用作游标源的表变量需要有一个主键。我已经添加了这个并且一切正常。

The answer appears to be that the table variable that is being used as the source of the cursor needs to have a primary key. I've added this and all works correctly.

写给空气的情书 2024-12-15 16:41:15

对游标不太熟悉,但从快速测试来看,您需要避免使用 STATIC 或 KEYSET 选项声明游标,然后对基础表的更改会反映在光标。

SET NOCOUNT ON;

DECLARE @WorkingTable TABLE(C int)

INSERT INTO @WorkingTable VALUES (1),(2),(3)

DECLARE @C int

DECLARE wt_cursor CURSOR 
DYNAMIC /*Or left blank but not STATIC or KEYSET*/
FOR 
SELECT C
FROM @WorkingTable

OPEN wt_cursor;

FETCH NEXT FROM wt_cursor 
INTO @C

DELETE FROM @WorkingTable

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @C;


    FETCH NEXT FROM wt_cursor 
    INTO @C;
END
CLOSE wt_cursor;
DEALLOCATE wt_cursor;

Not massively familiar with cursors but from a quick test this end you need to avoid declaring the cursor with the STATIC or KEYSET options then the changes to the underlying table are reflected in the cursor.

SET NOCOUNT ON;

DECLARE @WorkingTable TABLE(C int)

INSERT INTO @WorkingTable VALUES (1),(2),(3)

DECLARE @C int

DECLARE wt_cursor CURSOR 
DYNAMIC /*Or left blank but not STATIC or KEYSET*/
FOR 
SELECT C
FROM @WorkingTable

OPEN wt_cursor;

FETCH NEXT FROM wt_cursor 
INTO @C

DELETE FROM @WorkingTable

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @C;


    FETCH NEXT FROM wt_cursor 
    INTO @C;
END
CLOSE wt_cursor;
DEALLOCATE wt_cursor;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文