4

I have a staging table (in SQL SERVER 2008) with nullable fields.
I want to Insert or Update the records from the staging table to main table.
During this I want a comparison to be done

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

How can I embed the above condition in my insert and update statements?

2 Answers 2

10

The (sort of) equivalent 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;
Sign up to request clarification or add additional context in comments.

2 Comments

sorry i forgot to mention.. the condition must be on priority basis.
The priority is in the order you list them. So in this example priority would be given to the field1 expression followed by field2. The first qualifying expression is the one whose value is assigned to main.field1.
0
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 ), 
      ... ;

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.