为什么要使用存储过程
通过把处理封装在一个易用的单元中,可以简化复杂的操作。
1.由于不要求反复建立一系列处理步骤,因而保证了数据的一致性。(如果所有开发人员和应用程序都是用同一存储过程,则所有使用的代码都是相同的)
防止错误保证了数据的一致性
2.简化对变动的管理。如果表名、列名或者业务逻辑有变化,那么只需要更改存储过程的代码。
保证了安全性,通过存储过程限制对基础数据的访问,减少了数据讹误的机会
3.因为存储过程通常以编译过的形式存储,所以DBMS处理命令所需的工作量少,提高了性能。


声明一条统计行数量的存储过程
create procedure newsnum
as
declare @n INTEGER
select @n=COUNT(*)
from nrc_news
return @n
使用这条存储过程
declare @r int
execute @r=newsnum;
select @r;

create procedure typeorder @new_title varchar(50),@new_content varchar(50),@new_type integer
as
declare @type_num integer
select @type_num=count(@new_type)
from nrc_news
select @type_num=@type_num+1
insert into nrc_news(n_title,n_content,n_publishtime,t_id)
values(@new_title,@new_content,GETDATE(),@new_type)
return @type_num

create procedure newsorder @n_content varchar(50)
as
insert into nrc_news(n_content)
values(@n_content)

create proc up_addreply
@msgid int,
@userid int,
@replycontents varchar(1000),
@replytime varchar(30),
@replyip varchar(30)
as
begin transaction
declare @errorSum int
set @errorSum =0 --初始化为0
--添加回复
insert into t_reply
values(@msgid,@userid,@replycontents,@replytime,@replyip)

posted on 2015-10-12 17:24  baraka  阅读(300)  评论(0编辑  收藏  举报