create a cursor in ms sql server

create a cursor in ms sql server

Cursor is used to fetch records(rows) from any table sequentially and records can be manipulated, calculated as per your need.

To create a cursor use this sql query:

declare cursor_name cursor for
select id from tbl_Category
open cursor_name
fetch next from cursor_name into @Id
while @@fetch_status=0
insert into table_name(id) values (@Id)
fetch next from cursor_name into @Id

close cursor_name
deallocate cursor_name


Declare cursor is used  to declare a cursor and we need to open the cursor to use it.

fetch next is used to to fetch records sequentially and condition while @@fetch_status=0 verifies the sequence till end.

At last close the cursor by using close cursor and deallocate cursor.

Happy coding

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: