如何使用sp_executesql从SQL Server返回两个OUT参数

时间:2016-06-07 11:18:52

标签: sql-server

我想要返回总金额和页数。

我想将PageCount作为int返回,将TotalAmount作为十进制返回

  @SQL = 'select cast (row_number() over( ORDER BY |SortedColumn| |SortedOrder| ) as int)NO , * into #table  From  (Select SPM.Id as Id,SPM.SalePrice As PlanAmount,SPM.CreatedDate as CreatedDate,SPM.ExpertId as ExpertUserProfileId,P.Id as PatientId,ISNULL((P.FirstName +'' '' + P.LastName),'''') as PatientName 
              from SubscribedPlanByMember SPM
                JOIN Patient P ON 
                P.UserProfileId=SPM.MemberId
                ) SP Where  1=1 '
         + @Where  +
         ' select @x =  CEILING(CAST((CAST(@@rowcount AS FLOAT)/ CAST('+ltrim(@PageSize)+' AS FLOAT)) AS FLOAT))
         select *  from #table as t where NO between '+ltrim(@PageIndex-@PageSize+1)+' and '+ltrim(@PageIndex)+'  '

    SET @TotalAmount= CAST(( select Sum(SalePrice) as Amount from SubscriptionPlanOfExperts where ExpertId=@UserProfileId) as decimal)

          SET @SQL= REPLACE(@SQL, '|SortedColumn|', @sortedColumn);
            SET @SQL= REPLACE(@SQL, '|SortedOrder|', @sortedOrder);
 print(@SQL)

 exec sp_executesql @SQL, N'@x int out', @PageCount out 

1 个答案:

答案 0 :(得分:0)

在调用sp_executesql时有多个输出参数是完全可以接受的。请参阅以下MS支持文章:https://support.microsoft.com/en-gb/kb/262499

这提供了以下多个输出参数的示例:

DECLARE @SQLString NVARCHAR(500)
DECLARE @ParmDefinition NVARCHAR(500)
DECLARE @parmIN VARCHAR(10)
DECLARE @parmRET1 VARCHAR(30)
DECLARE @parmRET2 VARCHAR(30)
SET @parmIN=' returned'
SET @SQLString=N'EXEC Myproc @parm,
                             @parm1OUT OUTPUT, @parm2OUT OUTPUT'
SET @ParmDefinition=N'@parm varchar(10),
                      @parm1OUT varchar(30) OUTPUT,
                      @parm2OUT varchar(30) OUTPUT'

EXECUTE sp_executesql
    @SQLString,
    @ParmDefinition,
    @parm=@parmIN,
    @parm1OUT=@parmRET1 OUTPUT,@parm2OUT=@parmRET2 OUTPUT

SELECT @parmRET1 AS "parameter 1", @parmRET2 AS "parameter 2"

在您的情况下,您只需将sp_executesql调用修改为:

exec sp_executesql @SQL, N'@x int output, @TotalAmount decimal output', @PageCount=@x int output, @othervar=@TotalAmount decimal output