/*
作用是在用戶表中遷出用戶ID﹐Name,Age去逐條更新人員表中同ID的用戶信息。這也是游標的主要功能。
*/
/************************************************************************
Select * From user_
drop table user_
************************************************************************/
if not exists(select 1 from sysobjects where name='user_' and type='U')
Begin
CREATE TABLE [dbo].[user_](
[PId] [char](10) COLLATE Chinese_PRC_BIN NULL,
[PName] [char](10) COLLATE Chinese_PRC_BIN NULL,
[PAge] [int] NULL
) ON [PRIMARY]
End
GO
/************************************************************************
Select * From Person
drop table Person
************************************************************************/
if not exists(select 1 from sysobjects where name='Person' and type='U')
Begin
CREATE TABLE [dbo].[Person](
[PId] [char](10) COLLATE Chinese_PRC_BIN NULL,
[PName] [char](10) COLLATE Chinese_PRC_BIN NULL,
[PAge] [char](10) COLLATE Chinese_PRC_BIN NULL
) ON [PRIMARY]
End
GO
Delete From user_
Insert into user_(PId,PName,PAge) values('1','张三丰','100')
Insert into user_(PId,PName,PAge) values('2','李龙','22')
Insert into user_(PId,PName,PAge) values('3','Fuck','1000')
Insert into user_(PId,PName,PAge) values('4','西得里','18')
Insert into user_(PId,PName,PAge) values('5','王西风','20')
Delete From Person
Insert into Person(PId) values('1')
Insert into Person(PId) values('2')
Insert into Person(PId) values('3')
Insert into Person(PId) values('4')
Insert into Person(PId) values('5')
declare leads_curs cursor for --声明游标
select PId,PName,PAge from user_
declare
@ID Char(5),
@Name Char(8),
@strsql varchar(8000),
@Age Int,
@i int
declare
@stridx varchar(4)
Select @i=0
open leads_curs --打开游标
fetch leads_curs into @ID,@Name,@Age --提取第一行数据
select @stridx=convert(varchar(4),1)
select @strsql='update Person set liudinglong_'+@stridx+'= '''+convert(varchar(1),2)+''' '
print @strsql
while (@@Fetch_status=0)
begin
select @i=@i+1
select @stridx=convert(varchar(4),@i)
select @strsql='update Person Set PName='''+@Name+''',
PAge='''+convert(varchar(12),@Age)+'''
Where PId='''+@ID+''' '
Print @strsql
Print @stridx
exec(@strsql)
Fetch leads_curs into @ID,@Name,@Age --提取下一行数据,给 ID,Name,Age,游标下移一行
--Fetch Next From leads_curs @ID,@Name,@Age
end
close leads_curs
deallocate leads_curs
游标的使用的demo