SQL Update Multiple Fields FROM via a SELECT Statement

后端 未结 6 1549
生来不讨喜
生来不讨喜 2020-12-29 18:50

This works, but i would like to remove the redundancy. Is there a way to merge the update with a single select statement so i don\'t have to use vars?

    DE         


        
6条回答
  •  Happy的楠姐
    2020-12-29 19:13

    I would write it this way

    UPDATE s
    SET    OrgAddress1 = bd.OrgAddress1,    OrgAddress2 = bd.OrgAddress2,    
         ...    DestZip = bd.DestZip
    --select s.OrgAddress1, bd.OrgAddress1, s.OrgAddress2, bd.OrgAddress2, etc 
    FROM    Shipment s
    JOIN ProfilerTest.dbo.BookingDetails bd on  bd.MyID =s.MyID2
    WHERE    bd.MyID = @MyId 
    

    This way the join is explicit as implicit joins are a bad thing IMHO. You can run the commented out select (usually I specify the fields I'm updating old and new values next to each other) to make sure that what I am going to update is exactly what I meant to update.

提交回复
热议问题