存储过程中将sql语句结果赋值给变量
生活随笔
收集整理的這篇文章主要介紹了
存储过程中将sql语句结果赋值给变量
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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
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的話就會顯示行數
--存儲過程
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
--最關鍵在這句
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)
?
轉載于:https://www.cnblogs.com/newmin/archive/2009/06/22/1508314.html
總結
以上是生活随笔為你收集整理的存储过程中将sql语句结果赋值给变量的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 将枚举值转换为DropDownList等
- 下一篇: 在WinForm中通过HTTP协议向服务