您的位置:首页 > 数据库

创建临时表及如何使用游标SQL

2007-12-10 23:37 435 查看
select * from str--str是一个自建表,包括四个字段(id int,uname,age,mark,都是nvarchar类型,mark not null)
select * into #abc from str--创建临时表(局部)
select *,getdate() as ddd,'aaa' as fff into #ddd from str--或可直接在创建临时表的同时添加新列
select * into ##aaa from str--创建临时表(全局)
select * from #abc
select * from ##aaa
exists(select * from #abc)--检查局部临时表是否存在
exists(Select * from tempdb..sysobjects where name ='##aaa')--检查全局临时表是否存在
insert into #abc values('ddd','hhh','')--向临时表中插入数据,此处注意,原表中的mark字段
--是要求非空的,但在临时表中不受约束
select * from #abc order by id asc
drop table #abc--删除临时表

declare cus CURSOR for select * from #abc--此处注意,如果加了order by语句,则游标将自动变为只读属性
declare @a varchar(20)
set @a='a'
open cus
fetch next from cus--将游标定位到第一行(打开游标时的默认位置是在第一行之前)
while @@fetch_status=0--0表示成功执行FETCH语句.-1表示FETCH语句失败,例如移动行指针使其超出了结果集.-2表示被提取的行不存在
begin
set @a=@a+'k'
update #abc set mark=@a where current of cus--current of是游标所在的当前行
fetch next from cus
end
close cus
DEALLOCATE cus--删除游标
select * from #abc

--其中fetch next from cus可改写成fetch next from cus into @a,@b,@c.....目的是将游标结果集中的各列值放入到变量中
--INTO @variable_name[,...n]
--允许将提取操作的列数据放到局部变量中。列表中的各个变量从左到右与游标结果集中的相应列相关联。各变量的数据类型必须与相应的结
--果列的数据类型匹配或是结果列数据类型所支持的隐性转换。变量的数目必须与游标选择列表中的列的数目一致。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: