26 April 2017 Sudhanshu Ranjan 177

What is cursor in SQL Server with example.

A cursor is a set of rows together with a pointer that identifies a current row.

Or

Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis, its like recordset in the ASP and visual basic.

Cursor Example:

A New Table Employee_Data Created.

CREATE TABLE Employee_Data
(
Emp_ID INT Identity,
Emp_name Varchar(100),
Emp_Sal Decimal (10,2)
)

Data Inserted in Table

INSERT INTO Employee_Data VALUES ('Anees',1000);
INSERT INTO Employee_Data VALUES ('Rick',1200);
INSERT INTO Employee_Data VALUES ('John',1100);
INSERT INTO Employee_Data VALUES ('Stephen',1300);
INSERT INTO Employee_Data VALUES ('Sudhanshu Ranjan',1700);


Select * from Employee_Data

New Cursor Created -

Declare @Emp_ID as INT
Declare @Emp_name as varchar(100)
Declare @Emp_Sal as Decimal (10,2)
 
Declare MY_CURSOR CURSOR FOR
 
Select Emp_name from  Employee_Data (Nolock)
 
OPEN MY_CURSOR
    FETCH NEXT FROM MY_CURSOR INTO @Emp_name
        WHILE @@FETCH_STATUS = 0
        BEGIN
 -------------Perform Task here on Row by Row Basis---------
            PRINT @Emp_name-- 
 
        FETCH NEXT FROM MY_CURSOR INTO @Emp_name
        END
    CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR



In this article I try to explain about coursor. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

You can share at :

About Author
Sudhanshu Kumar Ranjan | Lead Engineer at HCL Technologies | Expertise in Microsoft Technology | Author | Blogger | Programmer
Know More
Connect with him on Facebook | Google+ | LinkedIn | Twitter

Recommended Post

Leave a comment

About Dotnet Cube

It's my blog - Dotnet Cube, where you will learn and get solutions about programming, web designing and development. I started this website to share my knowledge and experience which might help someone.

You can get more details about me and my blog at About Us page.

Subscribe Newsletter

Subscribe to our monthly newsletter to get the latest industry news, Media Group updates and our current specials.

Follow On Us...

Home | About | Advertise | Copyrights | Privacy | Contact | Admin

Copyrights © 2015-2017 dotnetcube.com. All rights reserved