0

I am trying to copy one table to another and if one of the items from the original table is null insert a default value instead.

INSERT INTO Table2(ColA, ColB, ColC)
SELECT Table1.ColA, Table1.ColB, (if Table1.ColC is null {'NewValue'} else {Table1.ColC})

No idea if I am anywhere close to a right answer.

3 Answers 3

1
INSERT INTO Table2 (ColA, ColB, ColC)
SELECT ColA, 
       ColB, 
       case when ColC is null 
            then 'NewValue' 
            else ColC
       end
from Table1

or

INSERT INTO Table2 (ColA, ColB, ColC)
SELECT ColA, 
       ColB, 
       coalesce(ColC, 'newValue')
from Table1
Sign up to request clarification or add additional context in comments.

Comments

1

Another method is to create a DEFAULT constraint on the table. Then, anytime you try to insert NULL you get the DEFAULT value instead:

ALTER TABLE Table2 ADD CONSTRAINT DF_Table2_ColC DEFAULT 'newValue' FOR ColC

Comments

0
INSERT INTO Table2 (ColA, ColB, ColC)
SELECT ColA, ColB, ISNULL(ColC, 'newvalue')
FROM Table1

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.