SQL Server存储过程

存储过程的使用

1.存储过程的定义
2. 存储过程的创建使用
3. 使用存储过程进行分页查询
4. 为什么要使用存储过程

存储过程的定义

 存储过程是一个预编译的sql语句 ,编译后可多次使用
 存储过程是一个预编译的SQL语句,优点是允许模块化的设计,
 就是说只需创建一次,以后在程序中就可以调用多次。
 如果某次操作需要执行多次SQL,使用存储过程比单纯SQL语句执行要快。可以用一个“execute 存储过程名 参数”命令来调用存储过程。
 他有无参无返回值,无参有返回值,有参无返回值,有参有返回值几种类型

存储过程的创建使用

  1. 无参无返回值存储过程的定义
 7. `--定义
if exists (select * from sysobjects where name='proc_Books' )
drop procedure proc_Books
go
create procedure proc_Books
 as
begin 
   select *from books 
end
--调用 execute 存储过程
go
declare @id int
execute proc_Books `
  1. 有参无返回值存储过程的定义
create procedure proc_Books

    --定义参数
	@id int 
as 
begin 
   select *from books  where ID=@id
end
--调用 execute 存储过程
go
declare @id int
execute proc_Books @id=6
  1. 无参有返回值的存储过程定义
--定义
if exists (select * from sysobjects where name='proc_Books' )
drop procedure proc_Books
go
create procedure proc_Books
 as
begin 
  print '无参有返回值的存储过程'
end
--调用 execute 存储过程
go
declare @id int
execute proc_Books 
  1. 有参有返回值的存储过程定义
--定义
if exists (select * from sysobjects where name='proc_Books' )
drop procedure proc_Books
go
create procedure proc_Books
 @id int
 as
begin 
  print @id
end
--调用 execute 存储过程
go
declare @id int
execute proc_Books @id=1
  1. 使用存储过程进行分页查询
--根据名称 页码 每页显条数  --输入参数
--返回查询条件的总记录数 --输出参数
--显示查询结果
go
if exists( select *from sysobjects where name='cp_select_book_byName')
drop proc cp_select_book_byName
go
create proc select_books_byName1
(
@name varchar(50),--根据名称查询
@pageIndex int,--第几页
@pageSize int,--每页条数
@rs int out --总记录数
)
as
begin
select top (@pageSize)  * from Books
where id not in (select top (@pageSize*@pageIndex-1) id from books where name like '%'+@name+'%' order by id )
and name like '%'+@name+'%' order by ID

select @rs=COUNT(*) from Books where  name like '%'+@name+'%'
end
go
declare @rs int
exec [dbo].[select_books_byName1] '水浒',3,5,@rs out

print @rs

为什么要使用存储过程

存储过程是指一组具有某种特殊功能的SQL语句集,常用于大型数据库中,也出现于开发过程中。程序员经常运用存储过程是由百于其具有以下优点:

一、响应时间上来说有优势:如果度你在前台处理的话。可能会涉及到多次数据库连接。但如果你用存储过程的话,就只有一次。存储过程可以给我们带来运行效率提高的好处。

二、安全上使用知了存储过程的系统更加稳定:程序容易出现 BUG 不稳定,而存储过程,只要数据库不出现问题,基本上是不会出现什么问题的

存储过程的优缺点

优势:响应时间上来说有优势,可以给我们带来运行效率提高的好处,且使用存储过程的系统更加稳定
缺点:维护性较差,相对于简单sql,存储过程并没有什么优势,并且在进行调试时比较困难

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值