Monday, August 10, 2009

Insert Vs Update in a DB

I have come across this problem a lot with my database coding. We have some data to insert into the database. Depending on whether the data is new or existing will determine whether we do an insert or an update statement on the database.

I find that this solves the problem very nicely,

if exists(select * from Table where key = 'rowId1')
begin
update Table set datavalue = 'newValue', datavalue1 = 'newValue' where key = 'rowId1'
end
else
begin
insert into Table values ('newValue','newValue', etc, etc)
end

Simple and sweet.

No comments: