简体   繁体   中英

Update records in one table from another only if records match

I am looking to update a column in Patientdemograpics called custom with a column in Patientdemographics2 called custom but only if the columns FirstName LastName and DateofBirth Match in both tables.

Update PatientDemographics
Set PatientDemographics.custom = PatientDemographics2.custom       
FROM            PatientDemographics INNER JOIN
                         PatientDemographics2 ON
                         Patientdemographics.FirstName = Patientdemographics2.FirstName and
                         Patientdemographics.LastName = Patientdemographics2.LastName  and 
                         Patientdemographics.DateofBirth = Patientdemographics.DateofBirth
                         where Patientdemographics.FirstName = Patientdemographics2.FirstName and
                         Patientdemographics.LastName = Patientdemographics2.LastName  and 
                         Patientdemographics.DateofBirth = Patientdemographics.DateofBirth

You have a typo in the last condition of the ON clause:

Patientdemographics.DateofBirth = Patientdemographics.DateofBirth

it should be:

Patientdemographics.DateofBirth = Patientdemographics2.DateofBirth

and also you have a useless WHERE clause since all its conditions are already applied in the ON clause.
Also use aliases to make the code simpler and more readable:

Update p
Set p.custom = p2.custom       
FROM PatientDemographics AS p INNER JOIN PatientDemographics2 AS p2 
ON
  p.FirstName = p2.FirstName and
  p.LastName = p2.LastName  and 
  p.DateofBirth = p2.DateofBirth

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM