Press enter to see results or esc to cancel.

SQl Server Cursor Simplified -part 1


Image

 

 

 

Cursor lets us navigate through Records in a Table,this concept is much complexed in many articles, here my attempt is to simplify it in my own words ( may be strange, but it works)

 

suppose there is a table table1

create table table1

(
cust_id int,
cust_name varchar(100)
)

Inserting 3 rows

insert into table1
select 1,’name1′
union
select 2,’name2′
union
select 3,’name3′

declare @custid as int

–Declaring Cursor
DECLARE c1 CURSOR READ_ONLY
FOR
SELECT cust_id
FROM table1

OPEN c1 — Open Cursor ( Now all cust_ids are thre in c1)

FETCH NEXT FROM c1 –Pointer to First position
INTO @custid
WHILE @@FETCH_STATUS = 0 ( when out of set it will be -1)
BEGIN

print @@FETCH_STATUS –printing status value
print @custid –printing fetched value
FETCH NEXT FROM c1 –Fetching from next row
INTO @custid

END
DEALLOCATE c1

 

Result

0
1
0
2
0
3
-1

Red colored one are status values for better understanding

hope this will help all those looking for cursors



Comments

Comments are disabled for this post