SQL查询 - 返回2表

时间:2011-03-17 18:24:56

标签: sql sql-server tsql

 declare @PageIndex int  
declare @PageSize int  
declare @CategoryID int 
declare @FromReleaseDate datetime 
declare @TillRelaseDate datetime


set @CategoryID =6
set @FromReleaseDate = '1.01.2000'
set @TillRelaseDate = '1.01.2022'
set @PageIndex =1
set @PageSize=2

begin
with filtered as (
  select ArticleList.ID as ID, ArticleList.CategoryID as CategoryID

  from (
     select  a.*, c.ID as cID, c.ParentID as ParentID, 
         ROW_NUMBER() over(order by ReleaseOn desc) as RowNum 
        from Article as a
        inner join Category as c

        on a.CategoryID=c.ID and (@CategoryID is null or a.CategoryID = @CategoryID  )
         where (a.ReleaseOn>=@FromReleaseDate)
         and (a.ReleaseOn <=@TillRelaseDate )

    ) 
    as ArticleList 
        where ArticleList.RowNum  between 
        (@PageIndex - 1) * @PageSize + 1 and @PageIndex*@PageSize

)



 select c.* from Article as a
   inner join Category as c on a.CategoryID=c.ID
 where
   c.id in (select CategoryID from filtered) 


  select a.* 
  from Article as a
  inner join Category as c on a.CategoryID=c.ID
  where a.id in (select id from filtered)

 end

我必须返回2张桌子。但我不能这样做,因为第二个查询中的过滤无法访问。有没有办法解决这个错误?

2 个答案:

答案 0 :(得分:1)

使用表变量或创建一个视图(如果您有权限),它代表您当前在CTE中的查询。

答案 1 :(得分:1)

使用表变量...

declare @filtered as table (
      ID int
    , CategoryID int
)

insert into @filtered
  select ArticleList.ID as ID, ArticleList.CategoryID as CategoryID

  from (
     select  a.*, c.ID as cID, c.ParentID as ParentID, 
         ROW_NUMBER() over(order by ReleaseOn desc) as RowNum 
        from Article as a
        inner join Category as c

        on a.CategoryID=c.ID and (@CategoryID is null or a.CategoryID = @CategoryID  )
         where (a.ReleaseOn>=@FromReleaseDate)
         and (a.ReleaseOn <=@TillRelaseDate )

    ) 
    as ArticleList 
        where ArticleList.RowNum  between 
        (@PageIndex - 1) * @PageSize + 1 and @PageIndex*@PageSize

with filtered as (
    select * from @filtered
)
... Rest of the query

select * from @filtered
相关问题