標籤:
為什麼要使用預存程序
通過把處理封裝在一個易用的單元中,可以簡化複雜的操作。
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 @[email protected]_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)
sql預存程序