mysql存储过程写法(创建一个简单的存储过程)

一、简介

简单记录一下存储过程的使用。存储过程是预编译SQL语句集合,也可以包含一些逻辑语句,而且当第一次调用存储过程时,被调用的存储过程会放在缓存中,当再次执行时,则不需要编译可以立马执行,使得其执行速度会非常快。

二、使用

创建格式 create procedure 过程名( 变量名 变量类型 ) as begin …….. end

e17e558f5f25488c8c00c858162da649noop.image_

create procedure getGroup(@salary int)asbegin   SELECT d_id AS '部门编号', AVG(e_salary) AS '部门平均工资' FROM employee  GROUP BY d_id   HAVING AVG(e_salary) > @salaryend     
4d4ccd11a9404187ab9eb5a57ef8a69dnoop.image_

调用时格式,exec 过程名 参数

exec getGroup 7000

三、在存储过程中实现分页

3.1 要实现分页,首先要知道实现的原理,其实就是查询一个表中的前几条数据

select top 10 * from table  --查询表前10条数据 
select top 10 * from table where id not in (select top (10) id  from tb) --查询前10条数据  (条件是id 不属于table 前10的数据中)

3.2 当查询第三页时,肯定不需要前面20 条件数据,则可以

select top 10 * from table where id not in (select top ((3-1) * 10) id  from tb) --查询前10条数据  (条件是id 不属于table 前10的数据中)

3.3 将可变数字参数化,写成存储过程如下

0ced577ff7d147c68e88613203928c68noop.image_

create proc sp_pager(    @size int , --每页大小    @index int --当前页码)asbegin    declare @sql nvarchar(1000)    if(@index = 1)         set @sql = 'select top ' + cast(@size as nvarchar(20)) + ' * from tb'    else         set @sql = 'select top ' + cast(@size as nvarchar(20)) + ' * from tb where id not in( select top '+cast((@index-1)*@size as nvarchar(50))+' id  from tb )'    execute(@sql)end
c2df9d09497a44b79e197707741c82c0noop.image_

3.4 当前的这种写法,要求id必须连续递增,所以有一定的弊端

所以可以使用 row_number(),使用select语句进行查询时,会为每一行进行编号,编号从1开始,使用时必须要使用order by 根据某个字段预排序,还可以使用partition by 将 from 子句生成的结果集划入应用了 row_number 函数的分区,类似于分组排序,写成存储过程如下

0f87c9ad003f461280da622fbe731e9anoop.image_

create proc sp_pager
(
    @size int,
    @index int
)
as
begin
    select * from ( select row_number() over(order by id ) as [rowId], * from table) as b
    where [rowId] between @size*(@index-1)+1  and @size*@index
end
c2af600d117545c69bb6b33fda71c1denoop.image_

本文内容来自网友供稿,文章观点仅代表作者本人,本站非盈利且无偿提供信息存储空间服务,不拥有所有权,如有文章有不实信息或侵犯了您的权益,请发送邮件至 cfseo1997@163.com 反馈核实,如需转载请注明出处:https://www.taobobolive.com/145380.html

(0)
上一篇 2023年3月23日 12:11:33
下一篇 2023年3月23日 12:15:53

相关推荐