Skip to content
Advertisement

Update a Column of a table after evaluating the status of columns from other tables

I have 3 tables, BaseTable, Test1Table and Test2Table

BaseTable
|TestID|Status| 
|TP1 |NULL|
|TP2 |NULL|
|TP3 |NULL|

Test1Table
|TestID|T1_Status|
|TP1   |1|
|TP2   |0|
|TP3   |1|

Test2Table
|TestID|T2_Status|
|TP1   |1|
|TP2   |0|
|TP3   |1|

This is what the output should be:

If Both Test1Table.T1_Status =1 and Test2Table.T2_Status =1 
   Update BaseTable.Status to 2 
Else 
  Update BaseTable.Status to 1

So for the above data set: Base Table should be

|TestID|Status|
|TP1   |2|
|TP2   |1|
|TP3   |2|

Advertisement

Answer

One method uses case and exists:

update basetable
   set status = (case when exists (select 1 from Test1Table t1 where t1.testId = basetable.testid and t1.status = 1) and
                           exists (select 1 from Test2Table t2 where t2.testId = basetable.testid and t2.status = 1) 
                      then 2 else 1
                 end);
                       
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement