Showing posts with label Update records row by row using cursor in sql. Show all posts
Showing posts with label Update records row by row using cursor in sql. Show all posts

Friday, January 7, 2011

Update records row by row using cursor in sql

How to loop through a table and update row by row using cursor in sql. ...basically looping through a table and updating record one by one in ms sql.

declare @cur1 cursor
declare @col1 varchar(10)
declare @col2 varchar(10)
declare @col3 varchar(10)
declare @col4 varchar(10)

set @cur1 = Cursor FOR SELECT column4,column1,column3 from myTable1

OPEN @cur1
FETCH NEXT FROM @cur1 into @col4, @col1, @col3
While @@FETCH_STATUS = 0
begin
select @col2=column2 from differentTable2 where someColumn=@col3

if @col2 is not null
begin
Update myTable1
set column2 = @col2
Where column4=@col4
end

FETCH NEXT FROM @cur1 into @col4, @col1, @col3
End
close cur1
deallocate cur1