0

I have two tables with the same structure but slightly different values. If a record of table 1 has some column values as null then that has to update to value in table 2, vice-versa.

Table 1

+--------------------+
|  id | exp | last   |
+--------------------+
| 1  | null | 4005   |
| 2  | null | null   |
| 3  | 10/19  | 1001 |
+--------------------+

Table 2

+-------------------+
|  id | exp | last  |
+-------------------+
| 1  | 08/23 | null |
| 2  | 07/21 | 3867 |
| 3  | null  | 1001 |
+-------------------+

Required Output

Table 3

+--------------------+
|  id | code | last  |
+--------------------+
| 1  | 08/23 | 4005  |
| 2  | 07/21 | 3867  |
| 3  | 10/19  | 1001 |
+--------------------+

Is this an outer join and if so how would I do this on SQL Server/Azure SQL?

3 Answers 3

1
select t1.id,
case when t1.exp is null then concat(t1.exp, t2.exp)  when t2.exp is null then concat(t1.exp, t2.exp) 
when t1.exp is not null then (t1.exp) when t2.exp is not null then (t2.exp)  end as exp,
case when t1.last is null then concat(t1.last, t2.last) 
when t2.last is null then concat(t1.last, t2.last) when t1.last is not null then (t1.last) 
when t2.last is not null then (t2.last) end as last
from Table1 t1 join Table2 t2 on t1.id=t2.id

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

A simple update statement with CASE or IIF will do:

UPDATE t1 
    IIF(t1.exp IS NULL, t2.exp, t1.exp)
    IIF(t1.last IS NULL, t2.exp, t1.exp)
FROM
    Table1 t1 
LEFT JOIN Table2 t2 
    ON t1.id = t2.id 

UPDATE t2
    IIF(t2.exp IS NULL, t1.exp, t2.exp)
    IIF(t2.last IS NULL, t1.exp, t2.exp)
FROM
    Table2 t2 
LEFT JOIN Table1 t1
    ON t1.id = t2.id 

Comments

0

With coalesce():

select 
  t1.id,
  coalesce(t1.exp, t2.exp) exp,
  coalesce(t1.last, t2.last) last,
from table1 t1 inner join table2 t2
on t2.id = t1.id

this gives precedence to the table1 values if they are not null.
Also if there is a case that the number of rows in the 2 tables is not the same, then you should use a left join from the table with the most rows to the other.
If you want to insert these rows to table3:

insert into table3 (id, exp, last)
select 
  t1.id,
  coalesce(t1.exp, t2.exp) exp,
  coalesce(t1.last, t2.last) last,
from table1 t1 inner join table2 t2
on t2.id = t1.id

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.