SQL Server 存储过程
1. 什么是存储过程?
存储过程是一个预编译的SQL语句,优点是允许模块化的设计,就是说只需创建一次,以后在程序中就可以调用多次。如果某次操作需要执行多次SQL,使用存储过程比单纯SQL语句执行要快。可以用一个“execute 存储过程名 参数”命令来调用存储过程。
2.怎么创建/修改/删除一个存储过程?
//创建存储过程,下面例子是一个有参存储过程
//无参存储过程即:create proc 存储过程名 as 需要执行的语句
create proc cp_Name
(
@name varchar(10)
)
as
select * from books where name like '%'+@name+'%'
//调用有参存储过程: execute 存储过程名 参数
//调用无参存储过程: execute 存储过程名
exec cp_name '红楼梦'
//删除存储过程
DROP proc cp_Name
//修改存储过程
alter proc cp_Name
(
@name varchar(10)
@typeid int out--out为输出参数关键字,调用存储过程时需定义变量接收
)
as
select @typeid=typeid from books where name like '%'+@name+'%'
3.利用存储过程进行分页
--分页
go
create procedure paging_procedure
(
@pageIndex int, -- 第几页
@pageSize int -- 每页包含的记录数
)
as
begin
select top (select @pageSize) * -- 这里注意一下,不能直接把变量放在这里,要用select
from (select row_number() over(order by name) as rownumber,*
from books) temp_row
where rownumber>(@pageIndex-1)*@pageSize;
end
-- 到时候直接调用就可以了,执行如下的语句进行调用分页的存储过程
exec paging_procedure @pageIndex=2,@pageSize=10;//查询第二页,每页10条数据。
执行效果如下图:
此时查询的是第二页👆
让我们来看看第一页👇