在T-SQL中有没有遍历表变量的方法?
DECLARE @table1 TABLE ( col1 int )
INSERT into @table1 SELECT col1 FROM table2
我也使用游标,但游标似乎不如表变量灵活。
DECLARE cursor1 CURSOR
FOR SELECT col1 FROM table2
OPEN cursor1
FETCH NEXT FROM cursor1
我希望能够以与游标相同的方式使用表变量。这样,我就可以在过程的一部分中对表变量执行一些查询,然后对表变量中的每一行执行一些代码。
任何帮助都是非常感谢的。
发布于 2009-10-16 14:03:07
向您的表变量添加标识,并执行从1到INSERT-SELECT的@@ROWCOUNT的简单循环。
试试这个:
DECLARE @RowsToProcess int
DECLARE @CurrentRow int
DECLARE @SelectCol1 int
DECLARE @table1 TABLE (RowID int not null primary key identity(1,1), col1 int )
INSERT into @table1 (col1) SELECT col1 FROM table2
SET @RowsToProcess=@@ROWCOUNT
SET @CurrentRow=0
WHILE @CurrentRow<@RowsToProcess
BEGIN
SET @CurrentRow=@CurrentRow+1
SELECT
@SelectCol1=col1
FROM @table1
WHERE RowID=@CurrentRow
--do your thing here--
END
发布于 2009-10-16 13:58:29
DECLARE @table1 TABLE (
idx int identity(1,1),
col1 int )
DECLARE @counter int
SET @counter = 1
WHILE(@counter < SELECT MAX(idx) FROM @table1)
BEGIN
DECLARE @colVar INT
SELECT @colVar = col1 FROM @table1 WHERE idx = @counter
-- Do your work here
SET @counter = @counter + 1
END
信不信由你,这实际上比使用游标更有效率和性能。
发布于 2015-06-17 15:17:41
我的两点意见..根据KM的回答,如果你想删除一个变量,你可以在@RowsToProcess上进行倒计时,而不是向上计数。
DECLARE @RowsToProcess int;
DECLARE @table1 TABLE (RowID int not null primary key identity(1,1), col1 int )
INSERT into @table1 (col1) SELECT col1 FROM table2
SET @RowsToProcess = @@ROWCOUNT
WHILE @RowsToProcess > 0 -- Countdown
BEGIN
SELECT *
FROM @table1
WHERE RowID=@RowsToProcess
--do your thing here--
SET @RowsToProcess = @RowsToProcess - 1; -- Countdown
END
https://stackoverflow.com/questions/1578198
复制相似问题