Simple Cursor Example

Below is the simple example to use Cursor in SQL

CREATE Database TestingDB
GO
CREATE TABLE tblTest(id int, name varchar(10))
Insert into tblTest Select 1,'White'
Insert into tblTest Select 2,'X'
GO
USE TestingDB
GO
DECLARE @id varchar(10) 
Set @id = ''
DECLARE @Name varchar(50)
Set @Name = ''
Declare @Detail varchar(1000)
Set @Detail = ''
DECLARE @getDetail CURSOR
SET @getDetail = CURSOR FOR
SELECT id,Name
FROM tblTest
OPEN @getDetail
FETCH NEXT
FROM @getDetail INTO @id,@Name
WHILE @@FETCH_STATUS = 0
BEGIN
	Set @Detail = @Detail + @id + @Name + Char(13)
FETCH NEXT
FROM @getDetail INTO @id,@Name
END
Select @Detail
CLOSE @getDetail
DEALLOCATE @getDetail 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s