簡單SQL存儲過程實例

簡單SQL存儲過程實例

摘自:http://blog.csdn.net/libra6956/article/details/5589173

实例1:只回去单一记录集的仓储过程。

银行存款表(bankMoney)的情节如下

Id

userID

Sex

Money

001

Zhangsan

30

002

Wangwu

50

003

Zhangsan

40

务求1:查询表bankMoney的内容的积存进程

create procedure sp_query_bankMoney
as
select * from bankMoney
go
exec sp_query_bankMoney

注* 
在利用进度中只需求把中的SQL语句替换为存储进度名,就足以了很便利呢!

实例2(向存储进程中传递参数):

投入一笔记录到表bankMoney,并询问此表中userID=
Zhangsan的所有存款的总金额。

Create proc insert_bank @param1 char(10),@param2 varchar(20),@param3
varchar(20),@param4 int,@param5 int output
with encryption ———加密
as
insert bankMoney (id,userID,sex,Money)
Values(@param1,@param2,@param3, @param4)
select @param5=sum(Money) from bankMoney where userID=’Zhangsan’
go
在SQL Server查询分析器中履行该存储进程的主意是:
declare @total_price int
exec insert_bank ‘004’,’Zhangsan’,’男’,100,@total_price output
print ‘总余额为’+convert(varchar,@total_price)
go

在此地再啰嗦一下存储进程的3种传回值(方便正在看那几个事例的朋友不要再去查看语法内容):

1.以Return传回整数

2.以output格式传诵参数

3.Recordset

传回值的不同:

output和return都可在批次程式中用变量接收,而recordset则传回到执行批次的客户端中。

实例3:使用带有复杂 SELECT 语句的简要过程

  上面的囤积进程从七个表的连接中回到所有作者(提供了人名)、出版的书籍以及出版社。该存储进度不应用任何参数。

USE pubs
IF EXISTS (SELECT name FROM sysobjects
         WHERE name = ‘au_info_all’ AND type = ‘P’)
   DROP PROCEDURE au_info_all
GO
CREATE PROCEDURE au_info_all
AS
SELECT au_lname, au_fname, title, pub_name
   FROM authors a INNER JOIN titleauthor ta
      ON a.au_id = ta.au_id INNER JOIN titles t
      ON t.title_id = ta.title_id INNER JOIN publishers p
      ON t.pub_id = p.pub_id
GO

  au_info_all 存储进程能够经过以下措施执行:

EXECUTE au_info_all

  实例4:使用带有参数的大致进度

CREATE PROCEDURE au_info
   @lastname varchar(40),
   @firstname varchar(20)
AS
SELECT au_lname, au_fname, title, pub_name
   FROM authors a INNER JOIN titleauthor ta
      ON a.au_id = ta.au_id INNER JOIN titles t
      ON t.title_id = ta.title_id INNER JOIN publishers p
      ON t.pub_id = p.pub_id
   WHERE  au_fname = @firstname
      AND au_lname = @lastname
GO

  au_info 存储进度可以由此以下格局执行:

EXECUTE au_info ‘Dull’, ‘Ann’
— Or
EXECUTE au_info @lastname = ‘Dull’, @firstname = ‘Ann’
— Or
EXECUTE au_info @firstname = ‘Ann’, @lastname = ‘Dull’

实例5:使用含有通配符参数的简便进程

CREATE PROCEDURE au_info2
@lastname varchar(30) = ‘D%’,
@firstname varchar(18) = ‘%’
AS
SELECT au_lname, au_fname, title, pub_name
FROM authors a INNER JOIN titleauthor ta
   ON a.au_id = ta.au_id INNER JOIN titles t
   ON t.title_id = ta.title_id INNER JOIN publishers p
   ON t.pub_id = p.pub_id
WHERE au_fname LIKE @firstname
   AND au_lname LIKE @lastname
GO

  au_info2 存储进程可以用各样重组执行。上边只列出了有的组成:

EXECUTE au_info2
— Or
EXECUTE au_info2 ‘Wh%’
— Or
EXECUTE au_info2 @firstname = ‘A%’
— Or
EXECUTE au_info2 ‘[CK]ars[OE]n’
— Or
EXECUTE au_info2 ‘Hunter’, ‘Sheryl’
— Or
EXECUTE au_info2 ‘H%’, ‘S%’

相关文章