存储过程的使用
1.存储过程的定义
2. 存储过程的创建使用
3. 使用存储过程进行分页查询
4. 为什么要使用存储过程
存储过程的定义
存储过程是一个预编译的sql语句 ,编译后可多次使用 存储过程是一个预编译的SQL语句,优点是允许模块化的设计, 就是说只需创建一次,以后在程序中就可以调用多次。 如果某次操作需要执行多次SQL,使用存储过程比单纯SQL语句执行要快。可以用一个“execute 存储过程名 参数”命令来调用存储过程。 他有无参无返回值,无参有返回值,有参无返回值,有参有返回值几种类型存储过程的创建使用
无参无返回值存储过程的定义
7. `--定义if exists (select * from sysobjects where name="proc_Books" )drop procedure proc_Booksgocreate procedure proc_Books asbegin select *from books end--调用 execute 存储过程godeclare @id intexecute proc_Books `有参无返回值存储过程的定义
create procedure proc_Books --定义参数 @id int as begin select *from books where ID=@idend--调用 execute 存储过程godeclare @id intexecute proc_Books @id=6无参有返回值的存储过程定义
--定义if exists (select * from sysobjects where name="proc_Books" )drop procedure proc_Booksgocreate procedure proc_Books asbegin print "无参有返回值的存储过程"end--调用 execute 存储过程godeclare @id intexecute proc_Books 有参有返回值的存储过程定义
--定义if exists (select * from sysobjects where name="proc_Books" )drop procedure proc_Booksgocreate procedure proc_Books @id int asbegin print @idend--调用 execute 存储过程godeclare @id intexecute proc_Books @id=1使用存储过程进行分页查询
--根据名称 页码 每页显条数 --输入参数--返回查询条件的总记录数 --输出参数--显示查询结果goif exists( select *from sysobjects where name="cp_select_book_byName")drop proc cp_select_book_byNamegocreate proc select_books_byName1(@name varchar(50),--根据名称查询@pageIndex int,--第几页@pageSize int,--每页条数@rs int out --总记录数)asbeginselect top (@pageSize) * from Bookswhere id not in (select top (@pageSize*@pageIndex-1) id from books where name like "%" @name "%" order by id )and name like "%" @name "%" order by IDselect @rs=COUNT(*) from Books where name like "%" @name "%"endgodeclare @rs intexec [dbo].[select_books_byName1] "水浒",3,5,@rs outprint @rs为什么要使用存储过程
存储过程是指一组具有某种特殊功能的SQL语句集,常用于大型数据库中,也出现于开发过程中。程序员经常运用存储过程是由百于其具有以下优点:
一、响应时间上来说有优势:如果度你在前台处理的话。可能会涉及到多次数据库连接。但如果你用存储过程的话,就只有一次。存储过程可以给我们带来运行效率提高的好处。
二、安全上使用知了存储过程的系统更加稳定:程序容易出现 BUG 不稳定,而存储过程,只要数据库不出现问题,基本上是不会出现什么问题的
存储过程的优缺点
优势:响应时间上来说有优势,可以给我们带来运行效率提高的好处,且使用存储过程的系统更加稳定
缺点:维护性较差,相对于简单sql,存储过程并没有什么优势,并且在进行调试时比较困难
来源:/content-2-698301.html