使用CTE更新表,然后删除不再有效的记录

时间:2018-07-24 19:23:25

标签: sql sql-server tsql common-table-expression sql-delete

在使用update语句中的适当值更新记录后,我随后尝试删除不再有效的记录。 我的代码如下,我不确定您将如何使用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

1 个答案:

答案 0 :(得分:1)

您不能以这种方式两次使用CTE,而是为什么不只使用OUTPUT clause从UPDATE语句中捕获信息,然后在DELETE语句中使用它。它将执行相同的操作而不必重复CTE查询(这可能会非常昂贵)。