Getting multiple values ​​in a SQL Server cursor

I have a cursor containing several columns from a row, which it returns, which I would like to process immediately. I notice that most of the examples that I see about how to use cursors show that they assign a specific column from the cursor to the scalar value one at a time, and then move on to the next line,

eg.

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 

I want to know if this can do the following:

  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 

Help is always appreciated.

+47
sql sql-server tsql cursor
Feb 11 '11 at 23:10
source share
1 answer

This should work:

 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; 
+86
Feb 11 '11 at 23:15
source share



All Articles