2014-05-11 57 views
0

我有一個複雜的查詢與「與」選擇​​分頁記錄,我想重用最後臨時表像的記錄計數的另一個用途:SQL如何重用臨時表

;with ProductCatIDs 
    as 
    (
     select 
      ID, ParentID, Name 
     from 
      [tbl_Categories] 
     where 
      ID = @CatID 
     union all 
     select 
      m.ID, m.ParentID, m.Name 
     from 
      [tbl_Categories] m 
     join 
      ProductCatIDs on ProductCatIDs.ID = m.ParentID 
    ), 

    ProductsFiltered as (

SELECT DISTINCT tbl_Products.* 
FROM   tbl_ProductCategories RIGHT OUTER JOIN 
         tbl_Products ON tbl_ProductCategories.ProductID = tbl_Products.ID 
WHERE  tbl_Products.Enabled = 'true' and (tbl_ProductCategories.CategoryID IN (

    select id 
    from ProductCatIDs 

))), 

#ProductsNumbered as (

Select *, ROW_NUMBER() OVER (order by ID DESC) as RowNumber FROM ProductsFiltered 

    ) 

SELECT * FROM #ProductsNumbered As tbl_Products 
    Where 
    RowNumber > @FirstRec 
    And RowNumber < @LastRec 



SELECT Count(*) FROM #ProductsNumbered 

最後一條語句返回一個錯誤無效對象名'#產品編號'

如何重複使用#ProductsNumbered來避免爲簡單計數器計算整個SP?

SELECT Count(*) FROM #ProductsNumbered 

回答

1

通過不使#ProductsNumbered您的公用表表達式的一部分,但是從你的ProductsFiltered手動插入進去。那麼你應該能夠重用它。

;with ProductCatIDs 
as 
    (
    ----SNIPPED TO KEEP POST SMALL------- 
), ProductsFiltered as (
    ----SNIPPED TO KEEP POST SMALL-------    
), 
    SELECT *, 
    ROW_NUMBER() OVER (order by ID DESC) as RowNumber 
    INTO #ProductsNumbered 
    FROM ProductsFiltered 

這樣你應該有共同的表表達式的範圍之外訪問您的臨時表,並可以在其上運行多個查詢。

+0

謝謝艾倫:) – Mertez