如何根据MAX写UPDATE?

时间:2011-11-26 12:23:21

标签: sql tsql

以下是MS SQL 2008数据库中我的2个表的简化示例

Documents [Id] AND 
DocumentsVersions [Id, DocumentId, IsCancelled]

我想将列IsActual(Bit NOT NULL)添加到DocumentVersions,它将表示该版本是否是最实际的版本。我通过检查同一文档的未取消版本中的Id是否最高来检查DocumentVersion是否实际。

我能写SELECT查询:

SELECT [t2].[Id] AS [value]
FROM (
    SELECT MAX([t0].[Id]) AS [value], [t0].[DocumentId]
    FROM [DocumentVersions] AS [t0]
    WHERE NOT ([t0].[IsCancelled] = 1)
    GROUP BY [t0].[DocumentId]
    ) AS [t1]
LEFT OUTER JOIN [DocumentVersions] AS [t2] ON ([t2].[Id] = [t1].[value]) 
     AND ([t1].[DocumentId] = [t2].[DocumentId]) 
     AND (NOT ([t2].[IsCancelled] = 1))

如何编写将IsActual = 1设置为满足这些条件的记录的更新查询?

2 个答案:

答案 0 :(得分:0)

尝试使用CTE:

;WITH maxNotCancelled(id)
AS
(
    SELECT [t2].[Id] AS [value]
    FROM (
        SELECT MAX([t0].[Id]) AS [value], [t0].[DocumentId]
        FROM [DocumentVersions] AS [t0]
        WHERE NOT ([t0].[IsCancelled] = 1)
        GROUP BY [t0].[DocumentId]
        ) AS [t1]
    LEFT OUTER JOIN [DocumentVersions] AS [t2] ON ([t2].[Id] = [t1].[value]) 
         AND ([t1].[DocumentId] = [t2].[DocumentId]) 
         AND (NOT ([t2].[IsCancelled] = 1))
)
UPDATE DocumentVersion
  SET d.IsActual = 1
FROM DocumentVersion d 
INNER JOIN maxNotCancelled m ON m.id = d.id

答案 1 :(得分:0)

UPDATE DocumentVersions dv
SET IsActual = 1 
WHERE dv.IsCancelled = 0
AND NOT EXISTS ( SELECT *
    FROM DocumentVersions nx
    WHERE nx.DocumentId = dv.DocumentId
      AND nx.IsCancelled = 0
      AND nx.id > dv.id -- assuming incrementing IDs
    );