繁体   English   中英

如何将多个CTE连接到临时表

[英]How to join multiple CTE's into a temp table

已为我提供了清理脚本的脚本,该脚本使用了大约85个临时表,建议我使用通用表表达式。

我有3个CTE,第一个是使用Union all将7个表组合在一起的结果。 其次是2个CTE。 该脚本运行到:

select * from CTE_1
Union all 
select * from CTE_2
Union all
select * from CTE_3

然后,我想将所有这些结果放入可重用的表中,以便随后可以使用各种case语句逻辑添加一些联接。 如何将它们放入临时表中,以便以后使用。

我希望减少临时表的数量,而不是将每个CTE放入一个临时表中,而我最好将多个CTE放入一个临时表中。 我目前有:

; with [CTE One] as (
  select 1 as col
),
  [CTE Two]  as (
  select 2 as col
),
  [CTE Three]  as (
  select 3 as col
)
select * from CTE_1
Union all 
select * from CTE_2
Union all
select * from CTE_3

您不能只使用into吗?

select *
into #temptable
from CTE_1
Union all 
select * from CTE_2
Union all
select * from CTE_3;

如果代码结构适当,我可能还会倾向于使用表变量。

或者..

    IF ( OBJECT_ID('tempdb..#temptable') IS NOT NULL )
        BEGIN
            DROP TABLE #temptable
        END

    CREATE TABLE #temptable
    (
        val int
    )



   ;
    WITH    [CTE One]
              AS ( SELECT   1 AS col
                 ),
            [CTE Two]
              AS ( SELECT   2 AS col
                 ),
            [CTE Three]
              AS ( SELECT   3 AS col
                 )
        INSERT  INTO #temptable (val)
                SELECT  *
                FROM    ( SELECT    *
                          FROM      CTE_1
                          UNION ALL
                          SELECT    *
                          FROM      CTE_2
                          UNION ALL
                          SELECT    *
                          FROM      CTE_3
                        ) T

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM