在SQL Server游标中获取多个值
我有一个游标,它包含了我想要一次处理的行中的多个列。 我注意到大部分我已经看到的关于如何使用游标的例子显示,他们将一个特定的列从游标分配给一个标量值,然后移动到下一行,
例如
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
帮助总是感激。
这应该工作:
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;