将部件作为临时表存储在cte中

时间:2014-08-25 11:45:25

标签: sql sql-server sql-server-2008

考虑以下cte

with Folders as 
(
    select a, b, c from foo
),
SubFolders as
(
    select 
          x.d
        , x.e 
    from
    (
        select 
              bla as d
            , boo as e
        from
            foobar
    ) x
    group by
        x.d,
        x.e
),
FullTable as
(
    select * from Folders
    cross join Subfolders
)

select * from Fulltable left join Subfolders on ...;

select s.d from Subfolders s; -- obviously does not work

(实际上,cte有更多的表达方式)。我现在想在我的脚本中查询Subfolders的结果集。其余的cte表达式我只需要一次。

这样做最优雅的方式是什么(加上:尽可能多地保留脚本)?我尝试了Combining INSERT INTO and WITH/CTE中提到的内容,但它给出了一个错误:The SELECT list for the INSERT statement contains fewer items than the insert list即使我肯定Subfolders只有2列。我做错了什么?

.
.
.
),
FullTable as
(
    select * from Folders
    cross join Subfolders
)

insert into #temp (
      Subfolders.d
    , Subfolders.e
)

select * from Fulltable left join Subfolders on ...;

...

2 个答案:

答案 0 :(得分:1)

绕道而行......

SELECT * INTO #SubFolders 
FROM
(   select  x.d
          , x.e 
    from
    (  select bla as d
            , boo as e
        from foobar
    ) x
    group by x.d, x.e
)A



;with Folders as 
(
    select a, b, c from foo
),
FullTable as
(
    select * from Folders
    cross join #SubFolders
)
select * from Fulltable left join #SubFolders on ...;

select s.d from #SubFolders s; -- this will work

答案 1 :(得分:0)

试试这个:

select Subfolders.d , Subfolders.e into #temp from Fulltable left join Subfolders on ...;