14、SQL Server 存储过程

SQL Server 存储过程

存储过程类似函数,可以重复使用。相对于函数,存储过程拥有更强大的功能和更高的灵活性。

存储过程中可以包含逻辑控制语句和数据操作语句,可以接受参数,输出参数,返回单个值或多个结果集。

存储过程带来的好处:

1、性能的提升

    存储过程执行时,第一次会进行编译和优化。但批处理T-SQL语句每次执行都需要预编译和优化,所以没有存储过程快。

2、易于维护

    存储过程创建后存储在数据库中,可以被程序多次调用执行。当需要修改存储过程时,对应用程序代码毫无影响。

3、安全性

    应用程序只需要调用存储过程名,给几个参数,而不是直接访问基础对象。需要赋予的不是增删改的权限,而是exec的权限。

系统存储过程

系统存储过程主要存储在master数据库中,以sp_开头,可以在所有数据库对象中使用。

常用的系统存储过程

exec sp_databases    --查看所有数据库
exec sp_tables        --查看所有数据表
exec sp_columns student --查看student表的所有列
exec sp_helpIndex student --查看student表的索引
exec sp_helpconstraint student --查看student表的约束
exec sp_helptext 'sp_databases' --查看定于语句
exec sp_rename oldName,newName --修改表、索引、列的名称
exec sp_renamedb webDB,newDB --修改数据库名称
exec sp_helpdb  webDB --查看数据库信息

用户定义存储过程

语法:

create proc | procedure proc_name
[
    {@parameter1 data_type} [=default] [out | output],
    {@parameter2 data_type} [=default] [out | output]
]
as
[begin]
    T-SQL代码
[end]

不带参数

if(exists(select * from sys.objects where name = 'proc_test'))
    drop proc proc_test  --删除
go
create proc proc_test --创建create 修改alter
as
    select * from student order by id desc
--调用
exec proc_test

执行存储过程使用execute关键字,可以简写为exec。在SQL Server 2012中得到加强,可以修改结果集中列名和类型。

execute proc_test 
with result sets
(
    (
        序号 varchar(5),
        姓名 varchar(10),
        性别 varchar(2),
        年龄 varchar(5),
        邮箱 varchar(5)
    )
)

输入参数

if(exists(select * from sys.objects where name = 'proc_test'))
    drop proc proc_test  --删除
go
create proc proc_test (@id int)
as
    select * from student where id = @id

--调用
exec proc_test 10

默认参数

if(exists(select * from sys.objects where name = 'proc_test'))
    drop proc proc_test  --删除
go
create proc proc_test (@id int = 10)
as
    select * from student where id = @id

--调用
exec proc_test      --10
exec proc_test 15 --15

输出参数

if(exists(select * from sys.objects where name = 'proc_test'))
    drop proc proc_test  --删除
go
create proc proc_test (
    @id int,        --输入参数
    @name varchar(10) out, --输出参数
    @age int output            --输入输出参数
)
as
begin --可写可不写
    select @name = name,@age = age from student where id = @id
end

--调用
declare @name varchar(10),@age int
exec proc_test 10,@name out,@age output
select @name,@age

不缓存

if(exists(select * from sys.objects where name = 'proc_test'))
    drop proc proc_test  --删除
go
create proc proc_test
with  recompile  --不缓存,每次都编译
as
    select * from student order by id desc
--调用
exec proc_test

加密

if(exists(select * from sys.objects where name = 'proc_test'))
    drop proc proc_test  --删除
go
create proc proc_test
with encryption  --加密后无法查看
as
    select * from student order by id desc
--调用
exec proc_test
exec sp_helptext proc_test
--提示对象 'proc_test' 的文本已加密。
原文地址:https://www.cnblogs.com/baidawei/p/4733453.html