Skip to main content

SQL Server Basics of Cursor

Cursor is a database objects to retrieve data from a result set one row at a time, instead of the T-SQL commands that operate on all the rows in the result set at one time. We use cursor when we need to update records in a database table in singleton fashion means row by row.

Life Cycle of Cursor

  1. Declare Cursor

    A cursor is declared by defining the SQL statement that returns a result set.
  2. Open

    A Cursor is opened and populated by executing the SQL statement defined by the cursor.
  3. Fetch

    When cursor is opened, rows can be fetched from the cursor one by one or in a block to do data manipulation.
  4. Close

    After data manipulation, we should close the cursor explicitly.
  5. Deallocate

    Finally, we need to delete the cursor definition and released all the system resources associated with the cursor.

Syntax to Declare Cursor

Declare Cursor SQL Comaand is used to define the cursor with many options that impact the scalablity and loading behaviour of the cursor. The basic syntax is given below

 DECLARE cursor_name CURSOR
 [LOCAL | GLOBAL] --define cursor scope
 [FORWARD_ONLY | SCROLL] --define cursor movements (forward/backward)
 [STATIC | KEYSET | DYNAMIC | FAST_FORWARD] --basic type of cursor
 [READ_ONLY | SCROLL_LOCKS | OPTIMISTIC] --define locks
 FOR select_statement --define SQL Select statement
 FOR UPDATE [col1,col2,...coln] --define columns that need to be updated 

Syntax to Open Cursor

A Cursor can be opened locally or globally. By default it is opened locally. The basic syntax to open cursor is given below:

 OPEN [GLOBAL] cursor_name --by default it is local 

Syntax to Fetch Cursor

Fetch statement provides the many options to retrieve the rows from the cursor. NEXT is the default option. The basic syntax to fetch cursor is given below:

FETCH [NEXT|PRIOR|FIRST|LAST|ABSOLUTE n|RELATIVE n]
FROM [GLOBAL] cursor_name 
INTO @Variable_name[1,2,..n] 

Syntax to Close Cursor

Close statement closed the cursor explicitly. The basic syntax to close cursor is given below:
 CLOSE cursor_name --after closing it can be reopen 

Syntax to Deallocate Cursor

Deallocate statement delete the cursor definition and free all the system resources associated with the cursor. The basic syntax to close cursor is given below:

 DEALLOCATE cursor_name --after deallocation it can't be reopen 

SQL SERVER – Simple Examples of Cursors

 CREATE TABLE Employee
(
 EmpID int PRIMARY KEY,
 EmpName varchar (50) NOT NULL,
 Salary int NOT NULL,
 Address varchar (200) NOT NULL,
)
GO
INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(1,'Mohan',12000,'Noida')
INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(2,'Pavan',25000,'Delhi')
INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(3,'Amit',22000,'Dehradun')
INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(4,'Sonu',22000,'Noida')
INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(5,'Deepak',28000,'Gurgaon')
GO
SELECT * FROM Employee 





SET NOCOUNT ON
DECLARE @Id int
DECLARE @name varchar(50)
DECLARE @salary int
 DECLARE cur_emp CURSOR
STATIC FOR 
SELECT EmpID,EmpName,Salary from Employee
OPEN cur_emp
IF @@CURSOR_ROWS > 0
 BEGIN 
 FETCH NEXT FROM cur_emp INTO @Id,@name,@salary
 WHILE @@Fetch_status = 0
 BEGIN
 PRINT 'ID : '+ convert(varchar(20),@Id)+', Name : '+@name+ ', Salary : '+convert(varchar(20),@salary)
 FETCH NEXT FROM cur_emp INTO @Id,@name,@salary
 END
END
CLOSE cur_emp
DEALLOCATE cur_emp
SET NOCOUNT OFF 

 


Summary

In this article I try to explain the basic of Cursor in SQL Server with a simple example. I hope after reading this article you will be able to understand cursors in Sql Server. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.


Comments

Popular posts from this blog

Basic SEO Explained: How Search Engines Really Work

Basic SEO Explained: How Search Engines Really Work Search Engine Optimization (SEO) is the process of improving your website so that it appears higher in search engine results pages (SERPs). SEO helps users find your content organically without paid ads and brings long-term traffic. If you are new to SEO, you should first read our complete on-page SEO guide for beginners to understand the basics clearly. How Search Engines Work (Step-by-Step) Search engines work in three main stages: crawling, indexing, and ranking. Understanding these steps is essential for building SEO-friendly websites. 1. Crawling Crawling is the process where search engines use bots (such as Googlebot) to discover new and updated pages. These bots follow links from one page to another across the web. Internal links help crawlers find your content faster. Learn more in our internal linking strategy guide . 2. Indexing After crawling, search engines analyze and store your pages in...

What Is Web Hosting? A Beginner’s Complete Guide

What Is Web Hosting? A Beginner’s Complete Guide Web hosting is an essential service that allows websites to be accessible on the internet. Without web hosting, a website cannot be viewed online. What Is Web Hosting? Web hosting is a service that stores your website files on a server and delivers them to users when they visit your website. How Web Hosting Works When a user types your website address, the browser sends a request to the hosting server, which then displays your website files. Types of Web Hosting Shared Hosting: Affordable and beginner-friendly VPS Hosting: Better performance and control Dedicated Hosting: Full server access Cloud Hosting: Flexible and scalable Why Web Hosting Is Important Good hosting improves website speed, security, and uptime. Conclusion Web hosting is the foundation of every website. Beginners should start with shared hosting and upgrade as their site grows. Frequently Asked Questions Is web hosting necessary? Ye...

How to Start a Blog Step by Step (Beginner Friendly)

How to Start a Blog Step by Step (Beginner Friendly) Starting a blog is an excellent way to share knowledge and build an online presence. With the right approach, anyone can start blogging. Choose a Blog Topic Select a topic you enjoy and can write about consistently. Select a Blogging Platform Popular platforms include Blogger and WordPress. Blogger is free and easy for beginners. Choose a Domain Name Your domain name should be simple, memorable, and related to your blog topic. Design Your Blog Use a clean, fast-loading theme that works well on mobile devices. Create Quality Content Focus on original, helpful, and easy-to-read content. Conclusion Blogging requires patience and consistency. With quality content, your blog can grow over time. Frequently Asked Questions Can I start a blog for free? Yes, platforms like Blogger allow free blogging.