您的位置:首页 > 数据库

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

2012-01-13 10:07 495 查看
游标中用到的函数,就是前一篇文章中创建的那个函数。

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

create procedure UpdateHKUNo    --存储过程里面放置游标
as
begin

declare UpdateHKUNoCursor cursor    --声明一个游标,查询满足条件的数据
for select psn_code from person where type='E' and hku_no is null

open UpdateHKUNoCursor    --打开

declare @noToUpdate varchar(20)    --声明一个变量,用于读取游标中的值
fetch next from UpdateHKUNoCursor into @noToUpdate

while @@fetch_status=0    --循环读取
begin
--print @noToUpdate
update person set hku_no=dbo.GetExtUserHKUNo() where psn_code=@noToUpdate
fetch next from UpdateHKUNoCursor into @noToUpdate
end

close UpdateHKUNoCursor    --关闭

deallocate UpdateHKUNoCursor    --删除

end

--exec UpdateHKUNo


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

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


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

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

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