您的位置:首页 > 数据库

Sql Server 游标(利用游标逐行更新数据)、存储过程

2014-10-23 16:11 344 查看
游标中用到的函数,就是前一篇文章中创建的那个函数。

另外,为了方便使用,把游标放在存储过程中,这样就可以方便地直接使用存储过程来执行游标了。

1 create procedure UpdateHKUNo    --存储过程里面放置游标
2 as
3 begin
4
5     declare UpdateHKUNoCursor cursor    --声明一个游标,查询满足条件的数据
6         for select psn_code from person where type='E' and hku_no is null
7
8     open UpdateHKUNoCursor    --打开
9
10     declare @noToUpdate varchar(20)    --声明一个变量,用于读取游标中的值
11         fetch next from UpdateHKUNoCursor into @noToUpdate
12
13     while @@fetch_status=0    --循环读取
14         begin
15         --print @noToUpdate
16         update person set hku_no=dbo.GetExtUserHKUNo() where psn_code=@noToUpdate
17         fetch next from UpdateHKUNoCursor into @noToUpdate
18         end
19
20     close UpdateHKUNoCursor    --关闭
21
22     deallocate UpdateHKUNoCursor    --删除
23
24 end
25
26 --exec UpdateHKUNo


另外,判断数据库中是否存在某一存储过程(Sqlserver 2000):

if exists (select * from sysobjects where name= 'UpdateHKUNo' and xtype ='P')
print 'yse'
else
print 'no'


既然说到存储过程,顺便记录多一些~

一、无参数的存储过程的创建、修改、执行、删除 

create procedure Myprocedure    --创建,修改时是alter
as
begin
--do something
select * from sysobjects
end

execute Myprocedure    --执行

drop procedure Myprocedure


二、带传入参数的存储过程: 

create proc ProcWithParam   --创建带有传入参数的存储过程
@id int        --参数没有用括号标记
as
begin
select * from sysobjects where id=@id    --使用参数
end

exec ProcWithParam 4 --执行时,在右边附带参数

drop proc ProcWithParam


三、带传出参数的存储过程(如果要传入、传出的,则把这个和前面第二个综合就好啦):)




View
Code

create proc ProuWithParamOut(@date datetime out)    --不带out,将被默认为传入参数!
as
begin
select @date=crdate from sysobjects where id=1    --传出参数只能是一个值,如果不带条件地查找,得到的数值是一个列表,将只取最后一个值
end

declare @date datetime    --声明一个变量,用于接收存储过程传出的参数
exec ProuWithParamOut @date out     --调用时,需要右边附带用于接收传出参数的变量
select @date as '存储过程传出的参数' --取得传出的参数,并自定义列名


注:传出参数的声明也可以像传入参数那样写,不需括号

create proc ProuWithParamOut    --不带out,将被默认为传入参数!
@date datetime out
as
begin
select @date=crdate from sysobjects where id=4    --传出参数只能是一个值,如果不带条件地查找,得到的数值是一个列表,将只取最后一个值
end


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