Dead Programmer
Dead Programmer

Reputation: 12575

SQL query to execute insert statement from the result of another sql query

Guys i have to do a insert in to a table when there is no record found. is it possible to do it with only sql query. i tried with case and if .

Upvotes: 0

Views: 188

Answers (2)

Joel Mansford
Joel Mansford

Reputation: 1316

Just add the condition of your 'IF' to the WHERE of the INSERT for example

INSERT INTO People
(FirstName,LastName,Email)
SELECT @FirstName,@LastName,@Email WHERE @Email NOT IN (SELECT Email FROM People)

If the email address already exists in the table then the SELECT will return no rows and hence no insert will take place

Upvotes: 3

ceth
ceth

Reputation: 45295

How about:

insert into table1 
   (select * from table2 where id not in
      (select id from table1))

Upvotes: 1

Related Questions