在SQL Server游标中获取多个值


75

我有一个游标,其中包含该行中的几列,它带回了我想立即处理的行。我注意到我看到的有关如何使用游标的大多数示例都显示了它们一次将游标中的特定列分配给一个标量值,然后移至下一行,

例如

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

帮助总是值得赞赏的。

Answers:


158

这应该工作:

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;

0

不要使用@@ 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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.