簡單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%’

相关文章