简体   繁体   中英

How do I update MSSQL table values from the contents of a second table using the ID from a third table to match the records?

I need to update table CSPM.TRACT with the values of CFPL.SVALUE where CSPM.ID = PM.PMPERMITID AND CSPM.TRACT IS NULL .

Here are the joins in place between the three tables: PM LEFT OUTER JOIN CFPL INNER JOIN CSPM ON CFPL.GCUSTOMFIELDPICKLISTITEM = CSPM.TRACTS ON PM.PMPERMITID = CSPM.ID

Try this -

 UPDATE CSPM
SET CSPM.TRACT = COALESCE (CSPM.TRACT, CFPL.SVALUE)
FROM CSPM
JOIN PM ON CSPM.ID = PM.PMPERMITID 
LEFT OUTER JOIN CFPL ON CFPL.GCUSTOMFIELDPICKLISTITEM = CSPM.TRACTS 

When dealing with outer joins sometimes the where clause restricts the normal outer join. Fortunately with a coalesce you can get around this complication and have a relatively straight-forward query:

update CSPM
set TRACT = coalesce(CSPM.TRACT, CFPL.SVALUE)
from CSPM  
  join PM on CSPM.ID = PM.PMPERMITD
  left join CFPL on CFPL.GCUSTOMFIELDPICKLISTITEM = CSPM.TRACTS 

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