Tuesday 2 June 2015

Cursor in Sql Server .

Cursor is a database object to retrieve data from result set row by row or one row at a time. Cursor is used when we want one by one row values and insert into another table one by one or update the table values one by one.

Create table article(art_acode varchar(5),art_jcode int,jobchapterid int);

insert some values in this table.

sql query for cursor:- 

DECLARE @name varchar(50)
DECLARE @Fname varchar(50)
DECLARE @Lname varchar(50)
DECLARE   @temp Table(name varchar(50),fname varchar(50),lname varchar(50))
DECLARE Emp_Cur CURSOR
STATIC for
Select Art_acode,Art_Jcode,JobChapterId from article where art_jcode=1876
open Emp_Cur
if @@CURSOR_ROWS>0
begin
FETCH NEXT FROM Emp_Cur into @name,@Fname,@Lname
While @@FETCH_STATUS =0
Begin
--print @name+' '+@Fname+' '+@Lname
insert into @temp(name,fname,lname)
values(@name,@Fname,@Lname)
FETCH NEXT FROM Emp_Cur into @name,@Fname,@Lname
end
end
close Emp_Cur
DEALLOCATE Emp_Cur


Select * from @temp

No comments:

Post a Comment

Note: only a member of this blog may post a comment.