Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (4k points)

I have a cursor containing several columns from the row it brings back that I would like to process at once. I notice most of the examples I've seeing on how to use cursors show them assigning a particular column from the cursor to a scalar value one at a time, then moving to the next row,

e.g.

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

What I want to know is if it's possible to do something like 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

1 Answer

0 votes
by (8.7k points)
edited by

SQL Server cursor: This SQL database cursor is referred to the set of TSQL logic which helps to traverse over different row.SQL server cursor is used for different purposes like Administration of database like taking database backups, or to perform any modification or maybe to perform some kind of Extract transform or load process.

Let’s have a look at how we fetch multiple values in the SQL server cursor:

DECLARE cursor_demo CURSOR FOR SELECT name, age, company FROM student_interns; 

DECLARE @goodName VARCHAR(256);

DECLARE @goodAge INT;

DECLARE @companyselected VARCHAR(40);

OPEN cursor_demo;

FETCH NEXT FROM db_cursor INTO @goodName, @goodAge, @companyselected;

WHILE @STATUS_COUNT = 0  

BEGIN  

FETCH NEXT FROM cursor_demo INTO  @goodName, @goodAge, @companyselected;

END;

CLOSE cursor_demo;

DEALLOCATE cursor_demo;

Related questions

0 votes
1 answer
asked Jan 29, 2020 in SQL by anmolj (9k points)
0 votes
1 answer
asked Jan 17, 2020 in SQL by anmolj (9k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...