更新每个相应选择的每一行

时间:2015-02-25 11:07:35

标签: mysql sql sql-server

我有一个返回一些旧的MemberShipIDs

的查询
select cst.MembershipID from Contestant cst
inner join User usr on usr.ID = cst.ID and usr.TypeOfUser = 0
order by usr.CreatedOn

我还有另一个查询会返回一些新更新的MemberShipIDs

select 
'CON' + '-' + convert(nvarchar(255), 
ROW_NUMBER() over(order by CreatedOn)) + '-' 
+ Right(Year(usr.CreatedOn),2)
from Contestant cst
inner join [dbo].[User] usr on usr.ID = cst.ID and usr.TypeOfUser = 0

现在,我希望使用新的MemberShipID值更新旧的MemberShipID值 对于每个匹配

1 个答案:

答案 0 :(得分:0)

您可以在join中使用update。这允许您计算子查询或CTE中的新值,并在update中分配它:

update cst
    set MembershipId = newval.newMembershipId
from Contestant cst join
     (select cst.MembershipID,
             'CON' + '-' + convert(nvarchar(255), ROW_NUMBER() over(order by CreatedOn)) + '-' + Right(Year(usr.CreatedOn),2) as newMembershipId
      from Contestant cst inner join
           [dbo].[User] usr
           on usr.ID = cst.ID and usr.TypeOfUser = 0
      ) newval
      on cst.MembershipID = newval.MembershipID;