如何从存储过程返回输出参数

时间:2014-02-06 12:25:02

标签: sql sql-server

我希望将总行数作为输出参数,稍后将从C#访问该参数。此查询给出错误 - 无效的对象名称“TBL”

ALTER PROCEDURE [dbo].[GetOrderDetails]
    @SortOrder nchar(10), 
    @ColName nvarchar(20),          
    @StartIndex int,
    @PageSize int,
    @RecordCount int output
AS
BEGIN
    SET NOCOUNT ON;

  DECLARE @Query nvarchar(MAX), 
          @Params nvarchar(MAX)

  SET @StartIndex = (@PageSize * (@StartIndex-1))+1
  SET @PageSize = @StartIndex + @PageSize - 1

  SET @Params = '@StartIndex int,
                 @PageSize int,
                 @RecordCount int'

  SET @Query = 'WITH TBL AS
                (
                 SELECT OD.OrderID,OD.ProductID,P.ProductName,OD.UnitPrice,
                 OD.Quantity,OD.Discount
                 FROM [Order Details] OD
                 LEFT JOIN Products P ON OD.ProductID = P.ProductID
                )

                SELECT @RecordCount = COUNT(*) FROM TBL ;

                SELECT * FROM
                (
                 SELECT ROW_NUMBER() OVER(ORDER BY '+@ColName+')Row, * 
                 FROM TBL
                )TEMP
                WHERE Row BETWEEN @StartIndex AND @PageSize
                ORDER BY Row '+@SortOrder

  execute sp_Executesql @Query,@Params,@RecordCount,@StartIndex,@PageSize
END

2 个答案:

答案 0 :(得分:1)

您正在使用名为 TBL 公用表表达式,该语句可用于其定义中的下一个SQL语句,并且会丢失给进一步的SQL语句。

由于您已经在

中使用了TBL一次
 SELECT @RecordCount = COUNT(*) FROM TBL ;

它现在已丢失,随后在动态查询的下一个SQL语句中无法使用,并出现错误: Invalid Object named TBL

SELECT * FROM
                (
                 SELECT ROW_NUMBER() OVER(ORDER BY '+@ColName+')Row, * 
                 FROM TBL
                )TEMP
                WHERE Row BETWEEN @StartIndex AND @PageSize

你可以试试这个

SET @Query = ';WITH TBL AS
                (
                 SELECT OD.OrderID,OD.ProductID,P.ProductName,OD.UnitPrice,
                 OD.Quantity,OD.Discount
                 FROM [Order Details] OD
                 LEFT JOIN Products P ON OD.ProductID = P.ProductID
                )

                --SELECT @RecordCount = COUNT(*) FROM TBL ; Remove this statement

                SELECT * FROM
                (
                 SELECT ROW_NUMBER() OVER(ORDER BY '+@ColName+')Row,
                         @RecordCount = COUNT(*) , * 
                 FROM TBL
                )TEMP
                WHERE Row BETWEEN @StartIndex AND @PageSize
                ORDER BY Row '+@SortOrder

答案 1 :(得分:1)

您可以使用表变量而不是CTE,这样您就可以计算,然后根据需要选择。 如果这样做,您需要修复执行调用:

  execute sp_Executesql 
    @Query,
    @Params,
    @StartIndex,
    @PageSize,
    @RecordCount OUTPUT

由于订单目前不正确且您遗失了OUTPUT

或者,您可以删除输出参数并将总计数作为第二个选择中的列返回;

SELECT * FROM
(
   SELECT ROW_NUMBER() OVER(ORDER BY '+@ColName+') Row
   , *
   , COUNT(*) OVER() AS TOTAL_ROWS