通过动态查询执行存储过程时,将值获取到输出变量中

时间:2018-01-22 12:28:08

标签: sql-server stored-procedures

我正在使用sql server 2008 r2,我创建了一个动态存储过程,因为这是我根据特定条件实现数据过滤的要求。我无法获得@RecordCount的价值

ALTER PROCEDURE [dbo].[sp_getAssetListAudit]
    @type nvarchar(20),
    @typeid nvarchar(5),
    @clientId nvarchar(5),
    @PageIndex nvarchar(5),
    @PageSize nvarchar(5),
    @RecordCount nvarchar(5) output 
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @SQL    nvarchar(max)

SET @SQL ='

select ROW_NUMBER() OVER ( ORDER BY ad.arid ASC )
AS rownum, ad.arid,ad.ast_code,ad.ast_descp,isnull(cat.name,'''') ''cat'',ISNULL(loc.name,'''') ''loc'',isnull(gp.name,'''') ''grp'',
isnull(cc.name,'''') ''cc'' ,
ad.ast_qty ''qty'' into #Results
from tbl_AssetDetails ad
left join tbl_Category cat on ad.ast_cat = cat.catid
left join tbl_Subcategory scat on ad.ast_subcat = scat.subcatid
left join tbl_Location loc on loc.lid = ad.ast_loc
left join tbl_Group gp on gp.gid = ad.ast_grp
left join tbl_CostCenter cc on cc.ccid = ad.ast_costcen
where ad.ast_status not in (3,-1) AND ad.clientId = '+@clientId+' AND ' 

IF(@type='cat')
SET @SQL = @SQL +' ad.ast_cat='+@typeid+' AND '
IF(@type='subcat')
SET @SQL = @SQL +' ad.ast_subcat='+@typeid+' AND '
IF(@type='loc')
SET @SQL = @SQL +' ad.ast_loc='+@typeid+' AND '
IF(@type='grp')
SET @SQL = @SQL +' ad.ast_grp='+@typeid+' AND '
IF(@type='cc')
SET @SQL = @SQL +' ad.ast_costcen='+@typeid+' AND '
IF(@type='ast')
SET @SQL = @SQL +' ad.arid='+@typeid+' AND '

SET @SQL = @SQL +' 1=1 '
SET @SQL =@SQL + ' SELECT '+@RecordCount+' = count(*) FROM #Results '
SET @SQL  = @SQL +' SELECT * FROM #Results WHERE rownum 
BETWEEN('+@PageIndex+' -1) * '+@PageSize+' + 1 AND((('+@PageIndex+' -1) * '+@PageSize+'+ 1) + '+@PageSize+') - 1 '

SET @SQL = @SQL + ' drop table #Results '

EXEC sp_executesql @SQL, @RecordCount OUTPUT

END

我无法获得@RecordCount的值,因此没有结果集。

2 个答案:

答案 0 :(得分:1)

您需要将值分配给OUTPUT参数:

SET @SQL =@SQL + ' SELECT @RecordCount = count(*) FROM #Results; '

您还需要将参数定义传递给sp_executesql,就像在@ wannuanguo的回答中一样。您还应该使用@typeid,@ pageindex等参数,而不是查询中的文字。

答案 1 :(得分:0)

为sp_executesql添加第二个参数:

EXEC sp_executesql @SQL, N'@RecordCount nvarchar(5) output',@RecordCount OUTPUT