ion
ion

Reputation: 1231

Conditional insert sql server

Let's consider this basic insert

insert into TableName (Col1,Col2,Col3) values (Val1,Val2,Val3)

i want this insert to be done only if Val1 !=null and Val3!=null How to accomplish this?

Upvotes: 3

Views: 10473

Answers (2)

BeachBlocker
BeachBlocker

Reputation: 246

insert into TableName (Col1,Col2,Col3) select Val1,Val2,Val3 where Val1 is not null and Val3 is not null

Upvotes: 2

Sjuul Janssen
Sjuul Janssen

Reputation: 1802

Is this what you're looking for?

IF (Val1 is not null AND Val3 is not null)
BEGIN 
    insert into TableName (Col1,Col2,Col3) values (Val1,Val2,Val3)
END 

On second thought BeachBlocker's answer is quite nice too. I've modified it a little:

insert into TableName (Col1,Col2,Col3) select Val1,Val2,Val3 where Val1 is not null and Val3 is not null

Upvotes: 3

Related Questions