且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

有没有一种方法可以在不使用游标的情况下遍历TSQL中的表变量?

更新时间:2023-09-10 16:23:46

首先,您应该绝对确保需要遍历每一行-基于集合的操作在我能想到的每种情况下都会执行得更快,并且通常会使用简单的代码.

First of all you should be absolutely sure you need to iterate through each row — set based operations will perform faster in every case I can think of and will normally use simpler code.

取决于您的数据,可能仅使用SELECT语句即可进行循环,如下所示:

Depending on your data it may be possible to loop using just SELECT statements as shown below:

Declare @Id int

While (Select Count(*) From ATable Where Processed = 0) > 0
Begin
    Select Top 1 @Id = Id From ATable Where Processed = 0

    --Do some processing here

    Update ATable Set Processed = 1 Where Id = @Id 

End

另一种替代方法是使用临时表:

Another alternative is to use a temporary table:

Select *
Into   #Temp
From   ATable

Declare @Id int

While (Select Count(*) From #Temp) > 0
Begin

    Select Top 1 @Id = Id From #Temp

    --Do some processing here

    Delete #Temp Where Id = @Id

End

您应该选择的选项实际上取决于数据的结构和数量.

The option you should choose really depends on the structure and volume of your data.

注意::如果您使用的是SQL Server,则***使用:

Note: If you are using SQL Server you would be better served using:

WHILE EXISTS(SELECT * FROM #Temp)

使用COUNT必须触摸表中的每一行,EXISTS只需要触摸第一行(请参见下面的约瑟夫的答案.

Using COUNT will have to touch every single row in the table, the EXISTS only needs to touch the first one (see Josef's answer below).