存储过程中将sql语句结果赋值给变量
生活随笔
收集整理的這篇文章主要介紹了
存储过程中将sql语句结果赋值给变量
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
create??procedure?procname
AS
declare?@recount?int
select?@recount=count(id)?from?school
--最關(guān)鍵在這句
select?@recount=count(id)?from?school
select?@recount=select?count(id)?from?school?--?錯(cuò)誤:這里就不再需要select了
set?@recount=count(id)?from?school?--?錯(cuò)誤這里只能用select不能用set
set?@getRecordSql='select?@recordcount=count(1)?from?'+@chart
exec?sp_executesql?@getRecordSql,N'@recordCount?int?output',@recordCount?output
N'@recordCount int output',@recordCount output
做一個(gè)參數(shù)的替換,如果測(cè)試一下:print @recordCount的話就會(huì)顯示行數(shù)
--存儲(chǔ)過(guò)程
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)
AS
declare?@recount?int
select?@recount=count(id)?from?school
--最關(guān)鍵在這句
select?@recount=count(id)?from?school
select?@recount=select?count(id)?from?school?--?錯(cuò)誤:這里就不再需要select了
set?@recount=count(id)?from?school?--?錯(cuò)誤這里只能用select不能用set
?如果school為一個(gè)@chart參數(shù)的話,上面方法就不適用了
應(yīng)該為:
?
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
做一個(gè)參數(shù)的替換,如果測(cè)試一下:print @recordCount的話就會(huì)顯示行數(shù)
?
?//示例:選擇最新的5條數(shù)據(jù)從20條開(kāi)始
?
execute?A_School_getNew?5,20--存儲(chǔ)過(guò)程
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)
?
轉(zhuǎn)載于:https://www.cnblogs.com/newmin/archive/2009/06/22/1508314.html
總結(jié)
以上是生活随笔為你收集整理的存储过程中将sql语句结果赋值给变量的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 将枚举值转换为DropDownList等
- 下一篇: 在WinForm中通过HTTP协议向服务