SQL SERVER – Simple Example of Cursor

UPDATE: For working example using AdventureWorks visit : SQL SERVER – Simple Example of Cursor – Sample Cursor Part 2

This is the simplest example of the SQL Server Cursor. I have used this all the time for any use of Cursor in my T-SQL.
DECLARE @AccountID INT
DECLARE
@getAccountID CURSOR
SET
@getAccountID = CURSOR FOR
SELECT
Account_ID
FROM Accounts
OPEN @getAccountID
FETCH NEXT
FROM @getAccountID INTO @AccountID
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT
@AccountID
FETCH NEXT
FROM @getAccountID INTO @AccountID
END
CLOSE
@getAccountID
DEALLOCATE @getAccountID

Reference: Pinal Dave (http://www.SQLAuthority.com), BOL

SQL Cursor, SQL Scripts
Previous Post
SQL SERVER – Shrinking Truncate Log File – Log Full
Next Post
SQL SERVER – Query to find number Rows, Columns, ByteSize for each table in the current database – Find Biggest Table in Database

Related Posts

196 Comments. Leave new

Leave a Reply