存储过程

定义:

一组为了完成特点定功能的SQL语句集合,编译后存储在数据库中,可以通过指定存储过程形成并给出参数执行。

语法

create proc | procedure pro_name
[{@参数数据类型} [=默认值] [output],
{@参数数据类型} [=默认值] [output],
....
]
as
SQL_statements

 

修改

alter proc proc_get_student
as
select * from student;

 

不带参数存储过程

创建:create proc proc_get_student
as
select * from student;
调用:exec proc_get_student;

 

带参数存储过程

创建:create proc proc_find_stu(@startId int = 1, @endId int = 2)
as
select * from student where id between @startId and @endId
默认参数根据需要设置

调用(默认参数):exec proc_find_stu;

调用(自定义参数):exec proc_find_stu 2, 4;

 

带输出参数存储过程

创建:create proc proc_getStudentRecord(
    @id int, --默认输入参数
@name varchar(20) out, --输出参数
@age varchar(20) output--输入输出参数
)
as
select @name = name, @age = age from student where id = @id and age = @age;
调用:
declare @id int,
@name varchar(20),
@temp varchar(20);
set @id = 7;
set @temp = 1;
exec proc_getStudentRecord @id, @name out, @temp output;
select @name, @temp;
print @name + '#' + @temp;

 

存储过程优缺点

优点:

    • 减少网络数据量,降低网络开销
    • 执行速度快,创建时编译一次,以后不需要重新编译。一般SQL每次执行都需要编译(不命中缓存时)
    • 多条语句批处理,减少数据库连接次数
    • 参数化,防止SQL注入
    • 可控制存储过程使用权限
    • 有些时候修改只需要修改存储过程,不需要修改程序代码

缺点:

    • 使用复杂的存储过程,但是数据库不擅长处理逻辑
    • 维护问题,不易调试,发现问题。表结构发生改变,涉及的存储过程修改问题。多副本部署问题。

posted @ 2019-06-25 20:32  vvf  阅读(1112)  评论(0编辑  收藏  举报