The order of using a cursor is: name cursor, open cursor, read data, close cursor, delete cursor. .
1. Regular loop execution of SQL
declare @i int --declaration
set @i= 1- initialize
while @i<= 50- execution conditions
begin
exec [dbo].[LineCalendar] @lineId= @i --executed SQL
set @i=@i+ 1-- add 1 to the variable after execution
end
2. Cursor loop (no transactions)
---cursor loop traversal--
begin
declare @a int,@error int
declare @temp varchar(50)
set @a=1
set @error=0
--declare cursor as Uid
declare order_cursor cursor for (select [Uid] from Student)
--open cursor--
open order_cursor
--start looping cursor variables--
fetch next from order_cursor into @temp
--determine the status of the cursor
--0 fetch statement successful
--1 fetch statement failed or this line is not in the result set
--the extracted row does not exist
while @@FETCH_STATUS = 0-- return to be FETCH the state of the last cursor during statement execution--
begin
update Student set Age=15+@a,demo=@a where Uid=@temp
set @a=@a+1
set @error= @error + @@ERROR --record each run sql is it correct after, 0 is correct
fetch next from order_cursor into @temp --go to the next cursor, there will be no loop
end
close order_cursor --close cursor
deallocate order_cursor --release cursor
end
go
3. Cursor loop (transaction)
---cursor loop traversal--
begin
declare @a int,@error int
declare @temp varchar(50)
set @a=1
set @error=0
begin tran --declaration transaction
--declare cursor as Uid
declare order_cursor cursor
for (select [Uid] from Student)
--open cursor--
open order_cursor
--start looping cursor variables--
fetch next from order_cursor into @temp
while @@FETCH_STATUS = 0-- return to be FETCH the state of the last cursor during statement execution--
begin
update Student set Age=20+@a,demo=@a where Uid=@temp
set @a=@a+1
set @error= @error + @@ERROR --record each run sql is it correct after, 0 is correct
fetch next from order_cursor into @temp --go to the next cursor
end
if @error=0
begin
commit tran --submit transaction
end
else
begin
rollback tran --rolling back transactions
end
close order_cursor --close cursor
deallocate order_cursor --release cursor
end
go