给出类似的更新声明:
UPDATE
UserAssesment
SET
AssessmentDate = comp.AssessmentDate
FROM
UserAssesment ua
INNER JOIN
vw_CompletedAssessments comp
On
ua.NatId = comp.NatId and
ua.FamilyName = comp.ClientLastName and
ua.GivenName = comp.ClientFirstName
WHERE
ua.HasCompletedAssessment <> 0
如果用户可以有多条匹配join子句的记录到vw_CompletedAssessments
,哪条记录将用于更新?有没有办法订购它以便使用最大或最小AssessmentDate
?
答案 0 :(得分:4)
你的UPDATE语法需要一些调整,见下文:
UPDATE ua
SET
ua.AssessmentDate = comp.AssessmentDate
FROM UserAssesment ua
INNER JOIN vw_CompletedAssessments comp
ON ua.NatId = comp.NatId and
ua.FamilyName = comp.ClientLastName and
ua.GivenName = comp.ClientFirstName
WHERE ua.HasCompletedAssessment <> 0
现在,如果您有多个值,并且想要从Comp表中选择一个特定值,那么您可以使用ROW_NUMBER函数,就像这样......
UPDATE ua
SET
ua.AssessmentDate = comp.AssessmentDate
FROM UserAssesment ua
INNER JOIN (SELECT *
, ROW_NUMBER() OVER (PARTITION BY NatId ORDER BY AssessmentDate DESC) rn
FROM vw_CompletedAssessments) comp
ON ua.NatId = comp.NatId
and ua.FamilyName = comp.ClientLastName
and ua.GivenName = comp.ClientFirstName
WHERE ua.HasCompletedAssessment <> 0
AND Comp.rn = 1
此查询会将ua.AssessmentDate更新为特定NatId的最新comp.AssessmentDate。同样,您可以看到如何使用行号操作结果。如果要将其更新为最旧的comp.AssessmentDate值,只需将row_number()函数中的order by子句更改为ASC,依此类推....
答案 1 :(得分:0)
如果找到多个匹配项,则会更新所有匹配项。
如果您只想更新一个,可以使用UPDATE TOP(1)吗?
如果您想保证要更新的订单的顺序,请尝试添加适当的ORDER BY子句。