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

时间:2018-01-17 20:50:23

标签: sql sql-server common-table-expression

我已经获得了一个清理脚本,它使用了大约85个临时表,我被建议使用公用表表达式。

我有3个CTE,第一个是使用Union all将7个表拉到一起的结果。接下来是另外2个CTE。该脚本最多运行:

Dim m_visioApp as Object
Set m_visioApp = CreateObject("visio.application")


Sub UpdateVsdFile(filename As String)

    m_visioApp.Documents.Open (filename)

    For Each pageObj In m_visioApp.ActiveDocument.Pages
        For Each oleObj In pageObj.OLEObjects
            If InStr(oleObj.progID, "Excel.Sheet") > 0 Then
                oleObj.Object.Activate
                oleObj.Object.Application.Worksheets(1).Cells(1, 1) = "Something"
                Call oleObj.Object.RefreshAll
            End If
        Next
    Next

    m_visioApp.ActiveWindow.DeselectAll

    m_visioApp.ActiveDocument.SaveAsEx filename, visSaveAsListInMRU

    m_visioApp.ActiveDocument.Close

End Sub

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

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

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

2 个答案:

答案 0 :(得分:1)

你不能只使用into吗?

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

如果代码结构合理,我可能也倾向于使用表变量。

答案 1 :(得分:1)

另外..

    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