#前言
在组合窗体的实现中用到了存储过程,在这里学习一下什么是存储过程。
#存储过程
存储过程(Stored Procedure)是在大型数据库系统中,一组为了完成特定功能的SQL 语句集,存储在数据库中,经过第一次编译后再次调用不需要再次编译,用户通过指定存储过程的名字并给出参数(如果该存储过程带有参数)来执行它。存储过程是数据库中的一个重要对象。——某度
##为什么用
我们使用SQL语句来实现我们的增删改查,大部分时候都是 很容易实现,但是当需要查询好多表、或者有几种操作一起的时候只是使用SQL语句一句一句实现就会有很多重复,这时候存储过程就很有优势了,他是完成你想实现的功能的SQL语句集。
存储过程与SQL语句对比
优势
1、提高性能
SQL语句在创建过程时进行分析和编译。存储过程是预编译的,在首次运行一个存储过程时,查询优化器对其进行分析、优化,并给出最终被存在系统表中的存储计划,在执行的过程中节省开销。
2、降低网络开销
存储过程只需要在提供必要的参数和名称即可。
3、便于进行代码移植
应用程序源代码处只需要参数和名称,所以在数据库中可以修改其存储过程,也是一种解耦的形式,大大提高了程序的可移植性。
4、更强的安全性
(1)可以对存储过程进行权限设置,避免非授权用户的访问。
(2)在通过网络调用的过程中,只有对执行过程的调用是可见的。恶意用户无法看到数据表和数据库对象名称,避免了嵌入自己的Transact-SQL语句或搜索关键数据。
(3)使用过程中使用参数,防止SQL注入攻击。
(4)可对进程进行加密,有助于对源代码的模糊处理。
创建存储
1、创建语法
create proc | procedure pro_name
[{@参数数据类型} [=默认值] [output],
{@参数数据类型} [=默认值] [output],
....
]
as
SQL_statements
2、创建不带参数存储过程
--创建存储过程
if (exists (select * from sys.objects where name = 'proc_get_student'))
drop proc proc_get_student
go
create proc proc_get_student
as
select * from student;
--调用、执行存储过程
exec proc_get_student
3、修改存储过程
--修改存储过程
alter proc proc_get_student
as
select * from student;
4、带参存储过程
--带参存储过程
if (object_id('proc_find_stu', 'P') is not null)
drop proc proc_find_stu
go
create proc proc_find_stu(@startId int, @endId int)
as
select * from student where id between @startId and @endId
go
exec proc_find_stu 2, 4;
5、带输出参数存储过程
if (object_id('proc_getStudentRecord', 'P') is not null)
drop proc proc_getStudentRecord
go
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 sex = @age;
go
--
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;
6、加密存储过程
--加密WITH ENCRYPTION
if (object_id('proc_temp_encryption', 'P') is not null)
drop proc proc_temp_encryption
go
create proc proc_temp_encryption
with encryption
as
select * from student;
go
exec proc_temp_encryption;
exec sp_helptext 'proc_temp';
exec sp_helptext 'proc_temp_encryption';