将 with cte 查询的结果插入临时表
Posted
技术标签:
【中文标题】将 with cte 查询的结果插入临时表【英文标题】:Inserting the result of a with cte query into a Temp Table 【发布时间】:2015-05-03 17:17:43 【问题描述】:我想将此查询的结果存储到临时表中:
WITH cOldest AS
(
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY [MyKey] ORDER BY SomeColumn DESC) AS rnDOB
FROM MyTable
)
SELECT
C.*
*** Insert into #MyTempTable *** This part doesn't work
FROM
cOldest C
WHERE
C.rnDOB = 1
提前致谢。
【问题讨论】:
【参考方案1】:假设这是针对 SQL Server 的:CTE 仅适用于 one 语句 - 所以你不能同时拥有 SELECT
和 INSERT
- 只需使用INSERT
:
WITH cOldest AS
(
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY [MyKey] ORDER BY SomeColumn DESC) AS rnDOB
FROM MyTable
)
INSERT INTO #MyTempTable(Col1, Col2, ....., ColN)
SELECT Col1, Col2, ...., ColN
FROM cOldest C
WHERE C.rnDOB = 1
这要求#MyTempTable
已经存在。如果您想使用 SELECT
创建它 - 使用以下语法:
WITH cOldest AS
(
.....
)
SELECT c.*
INTO #MyTempTable
FROM cOldest c
WHERE C.rnDOB = 1
【讨论】:
谢谢马克!我意识到为了能够导出临时表,它必须是全局临时表。进入##MyTempTable @marc_s以上是关于将 with cte 查询的结果插入临时表的主要内容,如果未能解决你的问题,请参考以下文章