分享Sql Server 存储过程使用方法
作者:just--like 时间:2024-01-13 06:42:36
一、简介
简单记录一下存储过程的使用。存储过程是预编译SQL语句集合,也可以包含一些逻辑语句,而且当第一次调用存储过程时,被调用的存储过程会放在缓存中,当再次执行时,则不需要编译可以立马执行,使得其执行速度会非常快。
二、使用
创建格式 create procedure 过程名( 变量名 变量类型 )as begin ........ end
create procedure getGroup(@salary int)
as
begin
SELECT d_id AS '部门编号', AVG(e_salary) AS '部门平均工资' FROM employee
GROUP BY d_id
HAVING AVG(e_salary) > @salary
end
调用时格式,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 将可变数字参数化,写成存储过程如下
create proc sp_pager
(
@size int , --每页大小
@index int --当前页码
)
as
begin
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
3.4 当前的这种写法,要求id必须连续递增,所以有一定的弊端
所以可以使用 row_number(),使用select语句进行查询时,会为每一行进行编号,编号从1开始,使用时必须要使用order by 根据某个字段预排序,还可以使用partition by 将 from 子句生成的结果集划入应用了 row_number 函数的分区,类似于分组排序,写成存储过程如下
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
来源:https://www.cnblogs.com/just-like/archive/2022/09/07/16659395.html
标签:Sql,存储过程
0
投稿
猜你喜欢
vue+element项目中过滤输入框特殊字符小结
2024-04-28 10:53:44
numpy.concatenate函数用法详解
2022-04-09 06:18:52
pytorch GAN生成对抗网络实例
2022-06-30 03:41:27
WEB打印大全
2023-06-30 14:35:15
python代码如何注释
2021-08-16 20:46:29
matplotlib绘制甘特图的万能模板案例
2022-07-11 20:24:08
antd table按表格里的日期去排序操作
2024-04-28 10:55:56
数据库触发器(Trigger)的一点使用心得
2024-01-28 14:21:29
在MySQL字段中使用逗号分隔符的方法分享
2024-01-17 23:34:19
sql格式化工具集合
2024-01-14 02:15:14
2008年个性设计挂历参考
2007-12-29 20:30:00
一文带你了解ChatGPT API的使用
2023-11-21 23:37:18
网站508规范(译)
2008-04-03 13:26:00
浅谈Python中函数的定义及其调用方法
2022-09-01 09:35:35
举例讲解Python的lambda语句声明匿名函数的用法
2021-05-29 13:02:53
python 利用opencv实现图像网络传输
2023-05-27 12:52:16
Python字典的核心底层原理讲解
2022-03-26 08:31:09
Python 使用类写装饰器的小技巧
2022-09-16 05:54:08
Golang爬虫框架 colly的使用
2024-02-02 13:40:55
Python 功能和特点(新手必学)
2022-02-23 04:11:25