【发布时间】:2021-11-26 18:58:56
【问题描述】:
在 Windows Server 中,我尝试使用多个 CTE 收集数据,并将它们插入到几个临时表中,以便稍后执行连接。下面是我得到的。 :
------TEMP TABLE SET UP------
IF EXISTS (
SELECT *
FROM tempdb.dbo.sysobjects
WHERE id = Object_id(N'tempdb..#LEFT')
)
BEGIN
DROP TABLE #LEFT
END
IF EXISTS (
SELECT *
FROM tempdb.dbo.sysobjects
WHERE id = Object_id(N'tempdb..#RIGHT')
)
BEGIN
DROP TABLE #RIGHT
END
------TEMP TABLE SET UP END------
------CTE SET UP------
; with
CTEfirst (1a, b, c, d) as
(select 1a, b, c, d from tableA)
, CTEone (a, b, c) as
(select a, b, c from table1)
),
CTEtwo (a, b, c) as (
(select a, b, c from table2)
),
CTEthree (a, b, c) as (
(select a, b, c from table3)
------CTE SET UP END------
select * into #LEFT from CTEone
union
select * from CTEtwo
union
select * from CTEthree
-----------------------------
/*At this point I am getting the issue to recognize CTEfirst when attempting to insert data into #RIGHT temp table unless I move the below portion below the previous section (prior to the unions) but then would encounter the issue of the overall query not recognizing the next CTE, CTEone.*/
select * into #RIGHT from CTEfirst
谢谢
【问题讨论】:
-
也标记您的数据库。你在用sql server吗?
-
你还没有定义“CTEfirst”
-
根据 CTE 的规范,在 CTE 之后只能有一个选择(UNION ALL 是第一个选择的延续)。
select * into #RIGHT from CTEfirst是不支持的第二条语句。事实上,如果你运行它,你会得到一个 Invalid object name 'CTEfirst'. 错误。根据规范:CTE 后面必须跟一个 SELECT 语句。不支持 INSERT、UPDATE、DELETE 和 MERGE 语句。 docs.microsoft.com/en-us/sql/t-sql/queries/… -
谢谢 jjthebig1 这是我害怕但不确定的。您的发现似乎已经回答了这个问题。
标签: sql common-table-expression temp