【发布时间】:2018-07-24 19:23:25
【问题描述】:
在更新语句中使用适当的值更新记录后,我尝试删除不再有效的记录。 我的代码如下,我不确定您将如何使用 CTE 中生成的值来删除表中的值, 任何帮助将不胜感激。
WITH CTE AS
(
SELECT C.CompressorId, C.CompressorSK, ROW_NUMBER() OVER(PARTITION BY C.Compressorid order by C.EffectiveDate) as RowNumber
FROM dimCompressor C
where CompressorId = 8
)
,CTE_MAX AS
(
SELECT CompressorId, MAX(CTE.RowNumber) AS MaxRow
FROM CTE
GROUP BY CompressorId
)
,CTE_SK AS
(
SELECT DISTINCT c.CompressorId, m1.MaxSK, m2.NextMaxSK
--, M1.MaxSK, M2.NextMaxSK
FROM CTE C
JOIN CTE_MAX M ON C.CompressorId = M.CompressorId
CROSS APPLY (
SELECT C1.CompressorSK AS MaxSK
FROM CTE C1
WHERE C1.CompressorId = M.CompressorId
AND C1.RowNumber = M.MaxRow
) M1
CROSS APPLY (
SELECT C2.CompressorSK AS NextMaxSK
FROM CTE C2
WHERE C2.CompressorId = M.CompressorId
AND C2.RowNumber = M.MaxRow - 1
) M2
)
UPDATE C1
SET C1.EffectiveDate = C2.EffectiveDate
FROM CTE_SK S
JOIN dimCompressor C1
ON S.MaxSK = C1.CompressorSK
JOIN dimCompressor C2
ON S.NextMaxSK = C2.CompressorSK
-- This is the part i need help with, i need to delete the row associated with the C2.COmpressorSK
delete FROM CTE_SK S
JOIN dimCompressor C1
ON S.MaxSK = C1.CompressorSK
JOIN dimCompressor C2
ON S.NextMaxSK = C2.CompressorSK
【问题讨论】:
-
您可能希望在合并 (link) 中使用带有删除子句而不是更新的 CTE。但我没有完成你的整个查询,对不起:)
-
你不能——你只能在直接跟在它后面的语句中引用一个 cte。没有办法(除了重新编写整个 cte 链之外)在两者都引用相同 ctes 的情况下进行更新和删除。
-
如果我要运行更新语句,然后将更新语句注释掉,然后运行删除语句呢?
-
@Dak 你具体使用什么数据库?那应该总是在标签中。此外,您的示例很神秘,与 MCVE 相去甚远。
-
@piezol 认为您没有阅读整个查询?我正在使用 SSMS 2017,它是一个关系数据库,我知道你的问题在问什么
标签: sql sql-server tsql common-table-expression sql-delete