Simple Example of Cursor

What is Cursor?


A cursor is a database object used by applications to manipulate data in a set on a row-by-row basis, instead of the typical SQL commands that operate on all the rows in the set at one time.
 
In order to work with a cursor, we need to perform some steps in the following order:
  1. Declare cursor
  2. Open cursor
  3. Fetch row from the cursor
  4. Process fetched row
  5. Close cursor
  6. Deallocate cursor
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.  
  1. DECLARE @AccountID INT  
  2. DECLARE @getAccountID CURSOR  
  3. SET @getAccountID = CURSOR FOR  
  4. SELECT Account_ID  
  5. FROM Accounts  
  6. OPEN @getAccountID  
  7. FETCH NEXT  
  8. FROM @getAccountID INTO @AccountID  
  9. WHILE @@FETCH_STATUS = 0  
  10. BEGIN  
  11. PRINT @AccountID  
  12. FETCH NEXT  
  13. FROM @getAccountID INTO @AccountID  
  14. END  
  15. CLOSE @getAccountID  
  16. DEALLOCATE @getAccountID  
Ebook Download
View all
SQL Jobs
Read by 0 people
Download Now!
Learn
View all