您的位置:首页 > 其它

存储过程建立临时表,通过游标增加数据

2009-12-11 17:16 309 查看
if exists(select * from sysobjects where name='pro_table')
drop proc pro_table --判断存储过程是否存在,如存在则删除
go
create proc pro_table ---创建存储过程
@sid int
as
begin
declare @sql nvarchar(200)

if(object_id('temptable') is not null)----创建临时表

begin
drop table temptable
end

create table temptable(sid int ,sname nvarchar(200),descriptions nvarchar(200))
---通过游标读取数据并将数据存入临时表中
declare tabl_cursor cursor for
select top 50 id,name from stest where sid=@sid ---声明游标
open tabl_cursor ----打开游标
declare @id int,@name varchar(200),@des nvarchar(200)
fetch next from tabl_cursor into @id,@name ----循环游标
while (@@fetch_status=0) ---判断游标是否到了尾端
begin
insert into temptable(sid,sname,descriptions)values(@id,substring(@name,1,20),convert(nvarchar(20),@id)+@name) ---将数据提交到临时表中
fetch next from tabl_cursor into @id,@name ----循环游标
end
close tabl_cursor ---关闭游标
deallocate tabl_cursor ---销毁游标

set @sql=N'select * from temptable'
exec sp_executesql @sql --执行查询临时表中的数据
drop table temptable --销毁临时表
end
GO

exec pro_table 2 --执行存储过程
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: