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

#cursor