declare @Parameter1 varchar(50)
declare cur_cursor cursor for (select fieldname1,fieldname2
from server.[database].[dbo].[table with data])
open cur_cursor
Fetch Next from cur_cursor into @Parameter1, @Parameter2
While @@fetch_status = 0
begin
update table
set fieldname = @Parameter1
where otherfieldname = @Parameter2
Fetch Next from cur_cursor into @Parameter1, @Parameter2
end
close cur_cursor
deallocate cur_cursor
The following cursor uses dynamic SQL, which can allow you to add columns to a table, or deduce which columns you wish to query.
declare @Parameter1 varchar(50)
declare @Parameter2 varchar(50)
declare @SQL nvarchar(4000)
declare cur_cursor cursor for (select fieldname1,fieldname2
from server.[database].[dbo].[table with data])
open cur_cursor
Fetch Next from cur_cursor into @Parameter1, @Parameter2
While @@fetch_status = 0
begin
set @SQL = 'update tablename
set fieldname = ''test' + @Parameter2 + '''where otherfield = ''' + @Parameter1 + ''''
exec sp_execute @SQL
Fetch Next from cur_cursor into @Parameter1, @Parameter2
end
close cur_cursordeallocate cur_cursor
There will be more to follow with more detailed explanations, examples of loops for larger datasets and nested loops, after the weekend.
Any questions let me know.
No comments:
Post a Comment