存儲過程幾種寫法

存儲過程幾種寫法

 

1)創建使用參數的存儲過程

Create Proc au_info @lastname varchar(40),@firstname varchar(20)

As

Select  au_lname,au_fname,title,pub_name

From ...

where au_fname=@firstname And au_lname=@lastname

Go

EXECUTE  au_info  ringer,anne

2)創建使用參數默認值的存儲過程,該存儲過程在沒有輸入參數的情況下將默認值得到的結果輸出

Create Proc au_info @lastname varchar(40)='ringer',@firstname varchar(20)='anne'

As

Select  au_lname,au_fname,title,pub_name

From ...

where au_fname=@firstname And au_lname=@lastname

Go

EXECUTE  au_info

 3)用顯式值替代參數默認值的存儲過程

Create Proc showind @table varchar(30) ='titles'

as

SELECT Table_Name=sysobjects.name,

INDEX_Name=sysindexes.name,index_id=indid

from sysindexes inner join sysobjects on sysobjects.id=sysindexes.id

where sysobjects.name=@table

EXECUTE showind authors

 

4)使用參數默認值NULL來創建存儲過程,在這種情況下如果沒有提供參數值,SQL將不會出錯顯示

Create Proc showind @table varchar(30) =Null

as

IF @table is NUll

print '請輸入參數'

else

SELECT Table_Name=sysobjects.name,

INDEX_Name=sysindexes.name,index_id=indid

from sysindexs inner join sysobjects on sysobjects.id=sysindexes.id

where sysobjects.name=@table

EXECUTE showind authors

5)使用包含通配符的參數默認值創建存儲過程

通配符包括(% , _ , [ ]和 [^]),注意需要用Like關鍵字

CREATE PROC au_info @lastname varchar(40)='r%' , @firstname varchar(20)='%'  AS

Select au_lname,au_fname,title,pub_name
from authors inner join titleauthor on authors.au_id=titleauthor.au_id
join titles on titleauthor.title_id=titles.title_id
join publishers on titles.pub_id=publishers.pub_id

where au_fname like @firstname
and au_lname like @lastname
GO

=====================================================

示例A. 創建使用參數的存儲過程下例創建一個在 pubs 數據庫中很有用的存儲過程。現在執行 au_info 存儲過程:EXECUTE au_info Ringer, AnneGO下面是結果集: au_lname au_fname title pub_name --------- --------- --------------------- ---------------- Ringer Anne The Gourmet Microwave Binnet &Hardley Ringer Anne Is Anger the Enemy? New Moon Books (2 row(s) affected)B. 創建使用參數默認值的存儲過程下例創建一個存儲過程 pub_info2,該存儲過程顯示作爲參數給出的出版商所出版的某本書的作者姓名。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章