ตัวอย่างการใช้ cursor ใน query analyzer หรือใน store procedure (mssql)
set nocount on
declare @POSITION_name varchar(100), @sql_id varchar(5) , @n int , @s1 varchar(5), @s2 varchar(5)
set @n = 1
declare cur cursor for
select POSNAME from [recruit].RCT_POSITION
open cur
fetch next from cur into @POSITION_name
while @@fetch_status=0
begin
set @s1 = cast(@n as varchar(5))
if len(@s1) = 1
begin
set @s1 = ‘00′ + @s1
end
else if len(@s1) = 2
begin
set @s1 = ‘0′ + @s1
end
–else if len(@s) = 3
–begin
–end
set @s1 = ‘PS’ + @s1
print @s1
update [recruit].mst_position set position_id = @s1 where position_name = @position_name
set @n = @n + 1
fetch next from cur into @POSITION_name
end
close cur
deallocate cur /* คืนทรัพยากร*/
set nocount off
การใช้ cursor ใน store, query analyzer
set nocount on
declare @POSITION_name varchar(100), @sql_id varchar(5) , @n int
declare cur cursor for
select POSNAME from [recruit].RCT_POSITION
open cur
fetch next from cur into @POSITION_name
while @@fetch_status=0
begin
print @position_name
insert into [recruit].mst_position (position_name) values(@POSITION_name)
fetch next from cur into @POSITION_name
end
close cur
deallocate cur /* คืนทรัพยากร*/
set nocount off