Using if / else in insert and update statements

I have a staging table (in SQL SERVER 2008) with fields with a null value.
I want to insert or update records from a staging table into the main table.
During this I want to make a comparison

Update main set main.field1 = ( if(staging.field1 isnull) then ---- else if(staging.field2 isnull) then ---- else then ) 

How can I insert the above condition into my insert and update instructions?

+4
source share
2 answers

The equivalent (view) is to use CASE expressions:

 UPDATE main SET main.field1 = CASE WHEN staging.field1 IS NULL THEN -- WHEN staging.field2 IS NULL THEN -- ELSE -- END; 
+10
source
 MERGE INTO main USING staging ON main.id = staging.id WHEN MATCHED THEN UPDATE SET field1 = COALESCE( staging.field1 , main.field1 ), SET field2 = COALESCE( staging.field2 , main.field2 ), ... ; 
0
source

Source: https://habr.com/ru/post/1401424/


All Articles