什么事存储过程?
存储过程是一个预编译的SQL语句
什么时候用存储过程?
如果某次操作需要执行多次SQL,使用存储过程比单纯SQL语句执行要快。可以用一个“execute 存储过程名 参数”命令来调用存储过程。
为什么要用存储过程?
优点是允许模块化的设计,就是说只需创建一次,以后在程序中就可以调用多次。
存储过程的优缺点有哪些?
优势:响应时间上来说有优势,可以给我们带来运行效率提高的好处,且使用存储过程的系统更加稳定
缺点:维护性较差,相对于简单sql,存储过程并没有什么优势,并且在进行调试时比较困难
存储过程有哪些用法?
存储过程的用法我们分为一下四种:
- 无参无返回值的存储过程
- 有参无返回值的存储过程
- 无参有返回值的存储过程
- 有参有返回值的存储过程
下面依次介绍其用法:
在Sql Server创建新数据库并且做好如下两张表,数据自行添加:
Books表
字段 | 字段含义 | 字段类型 |
---|---|---|
ID | 书籍编号,自增 | int |
Name | 书名 | nvarchar(50) |
TypeID | 书籍类型ID | int |
BookTypes表
字段 | 字段含义 | 字段类型 |
---|---|---|
ID | 类型编号,自增 | int |
Name | 类型名 | nvarchar(50) |
Nums | 该类型下书籍数量 | int |
无参无返回值的存储过程用法如下:
go
create proc cp_select_book
as
select * from EnRole.dbo.Books
--调用
exec cp_select_book
有参无返回值的存储过程用法如下:
go
create proc cp_select_book_byName
(
@name varchar(50)
)
as
select * from EnRole.dbo.Books where name like '%'+@name+'%'
--调用
exec cp_select_book_byName '西游记'
无参有返回值的存储过程用法如下:
go
create proc cp_select_booke_byNameExt
(
@recorRows int out
)
as
select @recorRows=COUNT(*) from EnRole.dbo.Books
--调用
go
declare @recorRows int
exec @recorRows out
select @recorRows 记录数
有参有返回值的存储过程,我们以分页来做例子,用法如下:
go
create proc cp_page_next
(
@name varchar(50), --按名称查询
@pageIndex int, --页数
@pageSize int, --每页记录数
@rs int out --总记录数
)
as
select top(@pageSize) * from EnRole.dbo.Books where ID not in (select top(@pageSize*(@pageIndex-1)) ID from EnRole.dbo.Books where Name like '%'+@name+'%' order by ID) and Name like '%'+@name+'%' order by ID
select @rs=count(*) from EnRole.dbo.Books where Name like '%'+@name+'%'
go
declare @rs int
exec cp_page_next '',1,5,@rs out
select @rs 总记录数