2011-03-17 83 views
0
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>[email protected]) 
     and (a.ReleaseOn <[email protected]) 

    ) 
    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个表。但我做不到,因为已过滤在第二个查询中无法访问。有没有办法解决这个错误?sql查询 - 返回2表

+0

开箱即用的,我能想到的临时表的.... – 2011-03-17 18:29:16

回答

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>[email protected]) 
     and (a.ReleaseOn <[email protected]) 

    ) 
    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 
1

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