views:

401

answers:

3

I have some data records that may or may not exist already in my database. Right now when I want to update these records, I have to keep track of whether I got them from the DB, or created them from scratch, so that I know whether to make an INSERT or UPDATE query. I could query the database just before writing to find out if the record exists, so that I don't have to hang onto this state for the object's lifetime, but that's more database overhead than I'd like. Does SQL have anything to help me out here?

I'm using SQL Server 2005, in case there's some sort of engine-specific solution.

+1  A: 

REPLACE INTO might be what you're looking for.

Edit: It looks like it might only be for MySQL... I'd delete this answer but other people using MySQL might find it helpful.

yjerem
He's using SQL SErver 2005, as per the question.
Mitch Wheat
It's MySQL only, and it's not a good choice anyway. REPLACE does a DELETE followed by an INSERT, which gets messy if you have foreign keys or triggers. Better to use INSERT...ON DUPLICATE UPDATE which is standard SQL.
Bill Karwin
A: 

There's not. I'm afraid the MERGE functionality wasn't introduced until SQL Server 2008.

Mitch Wheat
+4  A: 

This has been discussed here. Hope that helps.

Guy