数据库基础-存储过程

2018-11-28  本文已影响21人  一书文集

优点

-执行速度快,先将存储过程编译成二进制可执行代码
-模块式编程,在程序中被多次调用,并且当修改存储过程后,调用该存储过程的程序运行结果均会被修改,
提高了程序的可移植性
-减少网络流量 只需要使用存储过程名称及参数,
上传的字符数更少
安全性:需要访问数据表但又没有权限时
通过存储过程来存取

分类

系统,sp_ 为前缀,
用户自定义存储过程:由用户自行创建的存储过程。

使用 CREATE PROCEDURE 语句创建存储过程

create proc proc_st
as
select * from student
EXEC PROC_ST

创建带输入参数的存储过程

-- 通过学号查询姓名

create proc proc_query1
@query_no char(10)
as select StuName 
from student
where stuno = @query_no
create proc proc_query2
@qeury_no char(10) = '0463501107
'
as
select stuname
from student
where stuno = @query_no

-- 通过学号查询姓名,输入参数默认值设置为 NULL

create proc proc_query3
@query_no char(10) = null
as 
select stuName
from student
where stuNo = @query_no
create proc proc_query4
@query_no char(10) = null
as 
if @query_no is null
print '请你输入学号‘
else 
select stuname
from student 
where stuno = @query_no

创建带输出参数的存储过程

输出参数用 OUTPUT
-- 等差数列求和

create proc proc_sn
@n int, 
@n int output
as
declare @k int, @sum int
select @k=1, @sum=0
where @k < @m
while @x <= @m
  begin 
    select @sum = @sum+@x
    select @x = @x+1
  end
select @n = @sum

while( x <m)
 {sum = sum + x
  x++
}
n = sum
output  n
DECLARE @Y INT
EXEC PROC_SN 5,@Y OUTPUT
SELECT @Y

创建有多条 SQL 语句的存储过程

-- 通过特定课程名称查询课程的平均分、
最高分和
最低分,并查询出
成绩高于平均分的学生信息

create proc proc_multi
@couname_multi char(30)
as 
declare @avg_score decimal(5,1)
/* 通过特定课程名称查询课程的平均分、最高分和最低分 */
select avg(score) as 平均分,
           max(score) as 最高分,
            min(score) as 最低分
from score as s
  inner join course as c
  on s.couno = c.couno
where c.couname = @couname_multi

/* 将平均分赋值给变量 @COUNAME_MULTI */

select @avg_score = avg(score)
from score as s 
  inner join course as c
  on s.couno = c.couno
where c.couname = @couname_multi

/* 查询出成绩高于平均分的学生信息 */
select st.stuno, st.stuname,c.couname, s.score
from student as st
-- 连接
  inner join score as s
  on st.stuno = s.stuno

  inner join =c.couno
--查询条件
where c.couname = @couname_multi
and s.core > @avg_score

--调用
select *
from course
exec proc_multi 'sql设计'

修改存储过程

-修改咋们用alter
alter proc proc_st
as 
select * from student
where classno = ’20040001‘

删除存储过程

-删除drop.. 
DROP PROC PROC_ST

系统存储过程

系统存储过程可以从任何数据库中执行系统存储过程,而无需使用 master 数据库名称来完全限定该存储过程的名称。

sp_help Student
上一篇 下一篇

猜你喜欢

热点阅读