Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If Record Exists, Update Else Insert

I'm trying to move some data between two SQL Server 2008 tables. If the record exists in Table2 with the email from Table1 then update that record with the data from Table1, else insert a new record.

In Table1 I have a number of columns; first name, surname, email and so on.

I'm not quite sure how to structure the query to update Table2 if the email from Table1 exists or insert a new row if email from Table1 does not exist in Table2.

I tried doing a few searches on Google but most solutions seem to work by creating some stored procedure. So I wondered if anyone might know how to build a suitable query that might do the trick?

like image 417
doubleplusgood Avatar asked Oct 27 '09 11:10

doubleplusgood


People also ask

Can we use exists in update in SQL?

The SQL EXISTS condition is used in combination with a subquery and is considered to be met, if the subquery returns at least one row. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.


1 Answers

I think MERGE is what you want.

like image 62
APC Avatar answered Oct 30 '22 07:10

APC