2014-02-06 65 views
1

我希望將總行數作爲輸出參數,稍後將從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 '[email protected]+')Row, * 
       FROM TBL 
       )TEMP 
       WHERE Row BETWEEN @StartIndex AND @PageSize 
       ORDER BY Row '[email protected] 

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

回答

1

使用命名TBL公用表表達式這是availaible直到從它的定義下一個SQL語句,並失去了進一步的SQL語句。

既然你已經在

SELECT @RecordCount = COUNT(*) FROM TBL ; 

它現在失去了使用TBL一次,是不是在你的動態查詢的下一個SQL語句隨後availaible並給出錯誤:Invalid Object named TBL

SELECT * FROM 
       (
       SELECT ROW_NUMBER() OVER(ORDER BY '[email protected]+')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 '[email protected]+')Row, 
         @RecordCount = COUNT(*) , * 
       FROM TBL 
       )TEMP 
       WHERE Row BETWEEN @StartIndex AND @PageSize 
       ORDER BY Row '[email protected] 
+0

'='附近語法不正確。此外,它仍然是一個o/p參數吧? – Ruby

1

你可以使用表格變量而不是CTE,這樣你可以計算出來,然後按照你認爲合適的方式進行選擇。 如果你這樣做,你需要修復您的通話執行:

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

的順序是不正確當前和你缺少OUTPUT

或者,您可以刪除輸出參數並返回第二個選擇中列的總數;

SELECT * FROM 
(
    SELECT ROW_NUMBER() OVER(ORDER BY '[email protected]+') Row 
    , * 
    , COUNT(*) OVER() AS TOTAL_ROWS