数据库存储过程总结

存储过程
1:创建存储过程

create proc stu_proc1
as select count(*) from student
exec stu_proc1 执行

2:修改、删除、重命名

alter proc stu_proc1
as select * from student

drop proc stu_proc1
as select * from student

rename proc stu_proc1
as select * from student

3:参数存储过程
传入参数:

create proc stu_proc3
@pname char(3)
as select * from student where number=@pname
exec stu_proc3/'103/'

传出参数

create proc stu_proc5
@pname
@result char(8) output
as select @result=name from student where number=@pname
declare @a char(8)
exec stu_proc5 /'103/',@a output
print @a//select @a

亦可命名参数、明确指定

delcare @a char(8)
exec stu_proc5 @result=@a output,@pname=/'103/'
print @a

4:存储过程的复杂操作

使用带有复杂select语句的简单过程
下面的存储过程从两个表的联接中返回所有学生(提供了姓名)、所学课程。
该存储过程不使用任何参数。

use students
if exists(select name from sysobjects where name='/info_all/' and type=/'P/')
  drop procedure info_all
go 
create procedure info_all
as 
select stu.name,grade.course
from stu inner join grade on stu.number=grade.number
go

info_all存储过程可以通过以下方法执行:
execute info_all 或者 exec info_all

下面的存储过程从四个表的联接中返回所有作者(提供了姓名)出版的书籍以及出版社,该存储过程不使用任何参数

use upbs
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

练习1:制作存储过程显示所有年龄大于26的学生

create proc age1
as
select name from student
where year(getdate())-year(birthday)>26
exec age1

练习2:制作存储过程显示所有年龄大于指定大小的学生

create proc age2
@pdata int
as
select name from student
where year(getdate())-year(birthday)>@pdata
exec age2 26

存储过程的注意事项:可使用with recompile 和with encryption

两者都可放在参数之后,语句之前,其中with recompile会导致每次调用存储过程都会编译,效率变低,但执行效率可能优化,或加入到exec age with recompile中,则会根据需要创造新的查询计划多行储存过程。

create proc temp 
as 
select * from stu
select * from grade

转自博客:http://blog.csdn.net/jianxiong8814/article/details/2199380

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值