I have the following table that is comparing two similar tables:
Source | Part | Info 1 | Info 2 | ... | Info 12 | Description | Color |
---|---|---|---|---|---|---|---|
Table 1 | Wheel | Circle | ... | Long Distance | |||
Table 2 | Wheel | Circle | Rubber | ... | Long Distance | Wheel for vehicle | Black |
Table 1 | Seat | 4 Seats | ... | Comfortable | Brown | ||
Table 2 | Seat | Leather | 4 Seats | ... | Comfortable | Seat for vehicle | Brown |
I am trying to update the columns in Table 1 where it doesn't have the value of table 2.
I currently have the update query that works on a single field at one time but I am wondering if there is a way to make it dynamic and run through all the columns on a single run. Here is my working query right now:
UPDATE t
SET INFO2 = f.INFO2
FROM Table1 t
JOIN Table2 f ON f.PART = t.PART
WHERE t.INFO2 = '';
CodePudding user response:
Using a CASE expression to update NULL / empty string column, leave it as it is otherwise
UPDATE t
SET INFO2 = case when coalesce(t.INFO2, '') = '' then f.INFO2 else t.INFO2 end,
INFO3 = case when coalesce(t.INFO3, '') = '' then f.INFO3 else t.INFO3 end, ..
FROM Table1 t
JOIN Table2 f ON f.PART = t.PART ;