在 SQL Server 游标中获取多个值
Posted
技术标签:
【中文标题】在 SQL Server 游标中获取多个值【英文标题】:Get Multiple Values in SQL Server Cursor 【发布时间】:2011-06-25 21:20:11 【问题描述】:我有一个游标,其中包含我想一次处理的它带回的行中的几列。我注意到我看到的关于如何使用游标的大多数示例显示它们一次将游标中的特定列分配给标量值,然后移动到下一行,
例如
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
--Do Stuff with @name scalar value, then get next row from cursor
FETCH NEXT FROM db_cursor INTO @name
END
我想知道是否可以执行以下操作:
OPEN db_cursor
FETCH NEXT FROM db_cursor;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @myName = db_cursor.name;
SET @myAge = db_cursor.age;
SET @myFavoriteColor = db_cursor.favoriteColor;
--Do stuff with scalar values
FETCH NEXT FROM db_cursor;
END
我们总是感谢您的帮助。
【问题讨论】:
【参考方案1】:这应该可行:
DECLARE db_cursor CURSOR FOR SELECT name, age, color FROM table;
DECLARE @myName VARCHAR(256);
DECLARE @myAge INT;
DECLARE @myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
WHILE @@FETCH_STATUS = 0
BEGIN
--Do stuff with scalar values
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;
【讨论】:
【参考方案2】:不要使用@@fetch_status - 这将返回当前连接中最后一个游标的状态。使用下面的例子:
declare @sqCur cursor;
declare @data varchar(1000);
declare @i int = 0, @lastNum int, @rowNum int;
set @sqCur = cursor local static read_only for
select
row_number() over (order by(select null)) as RowNum
,Data -- you fields
from YourIntTable
open @cur
begin try
fetch last from @cur into @lastNum, @data
fetch absolute 1 from @cur into @rowNum, @data --start from the beginning and get first value
while @i < @lastNum
begin
set @i += 1
--Do your job here
print @data
fetch next from @cur into @rowNum, @data
end
end try
begin catch
close @cur --|
deallocate @cur --|-remove this 3 lines if you do not throw
;throw --|
end catch
close @cur
deallocate @cur
【讨论】:
以上是关于在 SQL Server 游标中获取多个值的主要内容,如果未能解决你的问题,请参考以下文章
如何在sql server和s-s-rs中获取多个值以及空值