SQL游标循环取值的两个实例
实例1:
declare @maxid int
declare @zhibanren nvarchar(30)
declare @shoujihao nvarchar(30)
declare @banci nvarchar(5)
declare @zhibanshijian datetime
select @maxid=ID from safe_message_zhibanbiao where day(getdate())=day(zhibanshijian)
if @maxid<>4
begin
declare Type_Cursor CURSOR FOR select zhibanren,shoujihao,banci,zhibanshijian from safe_message_zhibanbiao where day(getdate())=day(zhibanshijian)
open Type_Cursor
fetch next from Type_Cursor into @zhibanren,@shoujihao,@banci,@zhibanshijian
while(@@fetch_status=0)
begin
insert into safe_message_dangqianzhiban values (@zhibanren,@shoujihao,@banci,@zhibanshijian)
fetch next from Type_Cursor into @zhibanren,@shoujihao,@banci,@zhibanshijian
end
CLOSE Type_Cursor
DEALLOCATE Type_Cursor
end
declare @zhibanren nvarchar(30)
declare @shoujihao nvarchar(30)
declare @banci nvarchar(5)
declare @zhibanshijian datetime
select @maxid=ID from safe_message_zhibanbiao where day(getdate())=day(zhibanshijian)
if @maxid<>4
begin
declare Type_Cursor CURSOR FOR select zhibanren,shoujihao,banci,zhibanshijian from safe_message_zhibanbiao where day(getdate())=day(zhibanshijian)
open Type_Cursor
fetch next from Type_Cursor into @zhibanren,@shoujihao,@banci,@zhibanshijian
while(@@fetch_status=0)
begin
insert into safe_message_dangqianzhiban values (@zhibanren,@shoujihao,@banci,@zhibanshijian)
fetch next from Type_Cursor into @zhibanren,@shoujihao,@banci,@zhibanshijian
end
CLOSE Type_Cursor
DEALLOCATE Type_Cursor
end
实例2:
declare cur cursor
read_only
for select PName from Point
declare @name varchar(40)
open cur
fetch next from cur into @name
while (@@fetch_status =0)
begin
print @name
fetch next from cur into @name
end
close cur
deallocate cur
go
read_only
for select PName from Point
declare @name varchar(40)
open cur
fetch next from cur into @name
while (@@fetch_status =0)
begin
print @name
fetch next from cur into @name
end
close cur
deallocate cur
go