【问题标题】:Update a table with a CTE and then Delete the record thats no longer valid使用 CTE 更新表,然后删除不再有效的记录
【发布时间】: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


【解决方案1】:

您不能以这种方式使用 CTE 两次,但是,为什么不直接使用 OUTPUT clause 从 UPDATE 语句中捕获信息,然后在 DELETE 语句中使用它。它会做同样的事情,而不必重复 CTE 查询(这可能会非常昂贵)。

【讨论】:

    猜你喜欢
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    相关资源
    最近更新 更多