0

I want to perform an insert operation based on the select statement from another table in SQL Server.

I have built this:

INSERT INTO Table1
SELECT  table2.var1, table2.var2, 1, GETDATE(), 1, GETDATE(),0
FROM    table2

The values in Table1 are all NOT NULL, and there is a couple of record of table2.var2 where there is a null value, I want to skip the Null and continue with the operation.

1 Answer 1

1

You can filter the rows where table2.var2 is null in a WHERE clause.

INSERT INTO table1
            (<list of target columns>)
            SELECT table2.var1,
                   table2.var2,
                   1,
                   getdate(),
                   1,
                   getdate(),
                   0
                   FROM table2
                   WHERE table2.var2 IS NOT NULL;

You should also explicitly list the targeted columns in any INSERT so that statements don't break if the number or order of columns change in the target table.

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

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.