在 SQL Server 中是否有可能将一串 CTE 包装到 SQL 中的一个临时表中?
并非所有 CTE 都具有相同数量的列,也不具有相同的数据类型,因此 UNION ALL 是不可能的,我认为以下内容可能有效,但显然我遇到了语法错误:
SELECT * INTO #TEMP FROM (
;with firstCTE AS (
SELECT ColA
,ColB
,Colc
FROM tbl1
)
,secondCTE AS (
SELECT ColD
,ColE
FROM tbl2
)
,thirdCTE AS (
SELECT ColF
FROM tbl3
)
)
-- Selecting all of the data from the CTE's above
SELECT * FROM #TEMP
这取决于您想要实现的目标:
SELECT * INTO #TEMP FROM (
SELECT ColA
,ColB
,Colc
,CAST(NULL AS [use colD datatype]) AS ColD
,CAST(NULL AS [use colE datatype]) AS ColE
,CAST(NULL AS [use colF datatype]) AS ColF
FROM tbl1
UNION
SELECT
CAST(NULL AS [use colA datatype]) AS ColA
,CAST(NULL AS [use colB datatype]) AS ColB
,CAST(NULL AS [use colC datatype]) AS ColC
,ColD
,ColE
,CAST(NULL AS [use colF datatype]) AS ColF
FROM tbl2
UNION
SELECT
CAST(NULL AS [use colA datatype]) AS ColA
,CAST(NULL AS [use colB datatype]) AS ColB
,CAST(NULL AS [use colC datatype]) AS ColC
,CAST(NULL AS [use colD datatype]) AS ColD
,CAST(NULL AS [use colE datatype]) AS ColE
,ColF
FROM tbl3
)
-- Selecting all of the data from the CTE's above
SELECT * FROM #TEMP
CREATE TABLE #TMP1 (
SomeIntegerKey INT NOT NULL INDEX IX0 NONCLUSTERED
,ColA
,ColB
,Colc
)
INSERT INTO #TMP1 (
SomeIntegerKey
,ColA
,ColB
,Colc
)
SELECT
SomeIntegerKey
,ColA
,ColB
,Colc
FROM tbl1
CREATE TABLE #TMP2 (
SomeIntegerKey INT NOT NULL INDEX IX0 NONCLUSTERED
,ColD
,ColE
)
INSERT INTO #TMP1 (
SomeIntegerKey
,ColD
,ColE
)
SELECT
SomeIntegerKey
,ColD
,ColE
FROM tbl2
CREATE TABLE #TMP3 (
SomeIntegerKey INT NOT NULL INDEX IX0 NONCLUSTERED
,ColF
)
INSERT INTO #TMP1 (
SomeIntegerKey
,ColF
)
SELECT
SomeIntegerKey
,ColF
FROM tbl3
CREATE TABLE #TMPFINAL (
SomeIntegerKey INT NOT NULL INDEX IX0 NONCLUSTERED
,ColA
,ColB
,Colc
,ColD
,ColE
,ColF
)
INSERT INTO #TMPFINAL (
SomeIntegerKey
,ColA
,ColB
,Colc
,ColD
,ColE
,ColF
)
SELECT
tbl1.SomeIntegerKey
,tbl1.ColA
,tbl1.ColB
,tbl1.Colc
,tbl2.ColD
,tbl2.ColE
,tbl3.ColF
FROM tbl1
LEFT JOIN tbl2
ON tbl1.SomeIntegerKey = tbl2.SomeIntegerKey
LEFT JOIN tbl3
ON tbl1.SomeIntegerKey = tbl3.SomeIntegerKey