Click here to Skip to main content
15,884,986 members
Please Sign up or sign in to vote.
1.12/5 (4 votes)
See more:
How to write cursor in ms sql server 2008??
Posted
Comments
ZurdoDev 10-Aug-15 7:34am    
Many example online. Where are you stuck?

Here's a nice simple example I have given to coworkers to get them going. It iterates through the cursor and then inserts into a new table.

SQL
DECLARE @StudentID int, @FirstName varchar, @LastName varchar, @GraduateError int
DECLARE StudentCursor CURSOR FOR
SELECT StudentID, FirstName, LastName
FROM Student

OPEN StudentCursor

    FETCH NEXT FROM StudentCursor INTO @StudentID, @FirstName, @LastName

    WHILE @@FETCH_STATUS = 0
        BEGIN
            BEGIN
                INSERT INTO Graduate(StudentID, FirstName, LastName, AddUser, AddDate)
                VALUES(@StudentID, @FirstName, @LastName, 'administrator', GETDATE())

                SELECT @GraduateError = @@ERROR
                IF @GraduateError <> 0
                    BEGIN
                        PRINT '@GraduateError is ' + ltrim(rtrim(@GraduateError)) + '.'
                    END
                ELSE
                    BEGIN
                        PRINT 'Student Migrated to Graduate --> ' + CAST(@StudentID AS Varchar (20))
                    END

                FETCH NEXT FROM PopulationCursor INTO @StudentID, @FirstName, @LastName
            END
        END
    CLOSE StudentCursor
    DEALLOCATE StudentCursor
 
Share this answer
 
See here: MSDN: DECLARE CURSOR[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900