存储过程中将sql语句结果赋值给变量

博客围绕SQL存储过程展开,介绍了创建存储过程的方法,如统计表行数、选择特定范围数据等。还提及参数替换问题,当表名作为参数时,需用特定方式处理,给出了相应的SQL代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址:https://blog.youkuaiyun.com/courageously/article/details/5766466

 

create  procedure procname
AS
declare @recount int
select @recount=count(id) from school

--最关键在这句
select @recount=count(id) from school
select @recount=select count(id) from school -- 错误:这里就不再需要select了

set @recount=count(id) from school -- 错误这里只能用select不能用set


 如果school为一个@chart参数的话,上面方法就不适用了
应该为:

declare @getRecordSql nvarchar(100)
set @getRecordSql='select @recordcount=count(1) from '+@chart
exec sp_executesql @getRecordSql,N'@recordCount int output',@recordCount output

N'@recordCount int output',@recordCount output
做一个参数的替换,如果测试一下:print @recordCount的话就会显示行数


 //示例:选择最新的5条数据从20条开始

execute A_School_getNew 5,20

--存储过程

create procedure A_School_getNew
 @Size int,
 @StartIndex int
AS
declare @recount int
declare @Sql nvarchar(120)
select @recount=count(id) from school
set @Sql='select top '+convert(nvarchar,@Size)+'id,school_name from school where('+
 'ID not in(select top '+convert(nvarchar,@recount-@startIndex+@size)+
 ' id from school)) order by id desc';
execute (@Sql)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值