SQL Server資料庫開發(6.儲存過程)
一、儲存過程(procedure)
1.定義:用來執行管理業務或應用複雜的業務規則
儲存過程可以帶引數,也可以返回結果。
2.儲存過程可以包含資料操縱語句、變數、邏輯控制語句
3.儲存過程的優點:
3.1允許模組化程式設計
一次建立多次使用,並可獨立於原始碼而單獨修改
3.2執行速度更快
已經通過語法檢查和效能優化,儲存在伺服器,在執行時無需每次編譯
3.3減少網路流通量
一個需要百行T-SQL程式碼的操作可以由一條儲存過程單獨實現
3.4提高系統安全性
儲存過程的定義文字可以被加密,使使用者不能檢視其內容
可將儲存過程座位使用者存取資料的管理,取代原有資料表操作
4.儲存過程的分類
4.1系統儲存過程
由系統定義,存放在master資料庫中
類似c#中的系統函式
系統儲存過程的名稱都可以“sp_”開頭或“xp_“開頭
“sp_”開頭:用來進行系統的各項設定
“xp_“開頭:用來呼叫作業系統提供的功能
4.2使用者自定義儲存過程
由使用者子啊自己的資料庫中建立的儲存過程
類似c#中的使用者自定義函式
--儲存過程
IF exists(select * from sys.procedures where name='pr_stu_marks')
drop proc pr_stu_marks
--go 無引數
--create proc pr_stu_marks
--as
-- select StuInfo.stuid,stuName,subject,score
-- from StuInfo,StuMarks
-- where StuInfo.stuid=StuMarks.stuid
--go
--exec pr_stu_marks
--有引數
create proc pr_stu_marks(@name char(10))
as
select StuInfo.stuid,stuName,subject,score
from StuInfo,StuMarks
where StuInfo.stuid=StuMarks.stuid and
go
exec pr_stu_marks '田七'
IF exists(select * from sys.procedures where name='pr_stu_marks')
drop proc pr_stu_marks
go
--有預設引數 沒有傳遞引數時 查詢全部,有傳遞引數時,按條件查詢..
create proc pr_stu_marks(@name char(10)=null)
as
if @name is null
begin
select StuInfo.stuid,stuName,subject,score
from StuInfo,StuMarks
where StuInfo.stuid=StuMarks.stuid
end
else
begin
select StuInfo.stuid,stuName,subject,score
from StuInfo,StuMarks
where StuInfo.stuid=StuMarks.stuid and [email protected]
end
go
exec pr_stu_marks '田七'
--定義輸出引數
IF exists(select * from sys.procedures where name='pr_stu_marks')
drop proc pr_stucount
go
create proc pr_stucount(@boy int output,@gril int output)--output指定輸出
as
select @boy=COUNT(*) from StuInfo where stusex='男'
select @gril=COUNT(*) from StuInfo where stusex='女'
go
declare @boy int,@gril int
exec pr_stucount @boy output,@gril output
print '男:'+convert(char(1),@boy)+' 女:'+convert(char(1),@gril)
--丟擲異常
go
create proc devide(@a int,@b int,@c int output)
as
if(@b=0)
begin
raiserror ('0不能作為除數',10,2)
set @c=0
end
else
begin
set @[email protected]/@b
end
declare @c int
exec devide 2,3,@c output --不夠整數的小數部分完全截去
print @c