SQL SERVER – CURSOR – A SIMPLE EXAMPLE

Today one of my colleagues named sukanya Gopalakrishnan (junior s/w Engineer)   came and ask me some doubt about cursor. So I thought to write this topic which will help the fresher’s and also some experienced guys. Here I am explaining a simple cursor.

  • What is a cursor?

Cursor is a variable in SQL Server Database which is used for row-by row operations. The cursor is so named because it indicates the current position in the resultset.

  • Let us look this example.

Here I am just taking 2 columns  from a table and passing through the cursor and printing them.


  • CREATE PROCEDURE Usp_cursor_test
    AS
      BEGIN
          –Declaring the  variables needed for cursor to store data
          DECLARE @Name VARCHAR(50)
          DECLARE @EmptypeID INT
          –Declaring the Cursor cur_print For name and Emptypeid in the Employeedetails table 
          DECLARE cur_print CURSOR FOR
            SELECT name,
                   emptypeid
            FROM   employee.employeedetails
          –After declaring we have to open the cursor 
          OPEN cur_print
          –retreives the First row from cursor and storing it into the variables. 
          FETCH NEXT FROM cur_print INTO @Name, @EmptypeID
          — @@FETCH_STATUS returns the status of the last cursor FETCH statement issued against  
          — any cursor currently opened by the connection. 
          — @@FETCH_STATUS = 0 means The FETCH statement was successful. 
          — @FETCH_STATUS = -1 The FETCH statement failed or the row was beyond the result set. 
          — @@FETCH_STATUS = -2 The row fetched is missing. 
          WHILE @@FETCH_STATUS = 0
            BEGIN
                –Operations need to be done,Here just printing the variables 
                PRINT @Name
                PRINT @EmptypeID
                –retreives the NExt row from cursor and storing it into the variables. 
                FETCH NEXT FROM cur_print INTO @Name, @EmptypeID
            END
          –Closing the cursor 
          CLOSE cur_print
          — removes the cursor reference and relase cursor from memory 
          — very Important 
          DEALLOCATE cur_print
      END 
      
    Note: 

  • Once cursor is opened we have to close the cursor
  • After the usage cursor should be deallocated from the memory.
  • As a DBA , I will not recommend the usage of cursors in all scenarios because it affects performance, since for each result it will have a  network round trip which will cause a major performance issue in large data sets. You can make use of case statement instead of cursors for some scenarios.
print

28 thoughts on “SQL SERVER – CURSOR – A SIMPLE EXAMPLE

  1. Author’s gravatar

    Hai varun,
    Can u please include some DB performance tuning tips and its application scenario in next posts.

  2. Author’s gravatar

    super keep it up

  3. Author’s gravatar

    can you explain about implicit and explicit cursor with example?

  4. Author’s gravatar

    Hi Velu,

    i hope you got this question from an intervew. In sql server , if the cursor is automatically deallocated it is called Implicit cursor, if it is deallocated using the command dealocate cursor @cur , then it is explicit cursor.

    In the Oracle world a explicit cursor is a cursor you define in the declare section while an implicit cursor is what Oracle does for you each time you do not define an explicit one.

  5. Author’s gravatar

    plzzzzzzz help how to execute this

    1. Author’s gravatar

      you can execute this by execute option in sql server or by F5…

      Reply
  6. Author’s gravatar

    Its was really useful n easy to follow u…..

  7. Author’s gravatar

    This is one the best example of the cursor, but also give some extra creativity example for cursor…

  8. Author’s gravatar

    super…..

  9. Author’s gravatar

    HI VARUN,it’s really good n if possible can u post some imp interview questions on sql server for 2+ exp…Plz or send to my mail id(santhosh.niceguy@gmail.com).

  10. Author’s gravatar

    nice Article sir….this is very help full for fresher

  11. Author’s gravatar

    i would like to know how u get data if ID’s are there in present table and we have to get the data from other table when we do multiple selection??/

    1. Author’s gravatar

      Could you please explain the scenario bit more ?

      Reply
  12. Author’s gravatar

    Good example to start with for the newbies.

  13. Author’s gravatar

    Hi Varun,

    Thanks for cursor example, in additon to the above example can you alter the same logic using CASE Statement.

    Thanks in advance,
    Pradeep

  14. Author’s gravatar

    very good artical for beginners

    thanku so much

  15. Author’s gravatar

    Hi Varun.! This is very good article about cursors. It’s helped me alot.
    And also i want know about SQL Profiler, so could you please write the article about this.???
    Yugandhar

  16. Author’s gravatar

    Thanks for cursor example, in additon to the above example can you alter the same logic using CASE Statement.

  17. Author’s gravatar

    nice

  18. Author’s gravatar

    Hi, I do thin thios is an excellnt site. I stumbledupon it 😉 I’m going to come back yet again since i have bookmarked it.
    Money and freedom is the best way to change,
    may you be rich and continue to guide other people.

  19. Author’s gravatar

    its very UseFul

  20. Author’s gravatar

    Could You Explain Triggers With Examples For Beginners?…

  21. Author’s gravatar

    Varun,
    Can u pls tell me actually where i can use this Cursor in Sql Server even it have performance issues?

  22. Author’s gravatar

    nice

  23. Author’s gravatar

    hello varun

    can u explain how to add cursor in any sql jobs..plz..

    Thank you

    1. Author’s gravatar

      Can u refine this question?

      Reply
  24. Author’s gravatar

    Does your site have a contact page? I’m having trouble locating it but, I’d like
    to shoot you an e-mail. I’ve got some creative ideas for your blog you might be interested in hearing.
    Either way, great blog and I look forward to seeing it expand over time.

  25. Author’s gravatar

    good post !!!

Leave a Reply

Your email address will not be published. Required fields are marked *


eight + = 10