user278618
user278618

Reputation: 20232

Insert or update if record is in table

I have a tables Cars and CarDescriptions

cars: IDCar(int, PK, autoincrement) carsDesciptions(IDDescription, Header(nvarchar),Content(nvarchar),idCar(int,FK)

In application I am adding cars and editing existing ones.

My problems:

1.How to save changed Car with descriptions in database ??

I have ID of Car, and I have ID's of Descriptions

Class CarDescirption doesn't have any pool like IsChanged, so

I don't wanna do something like :

  1. delete from carsdescriptions where idcar=@idcar
  2. insert into cardescriptions (, @Header,@Content,@IDCar)

the record must be updated if is in table, and inserted if doesn't exist in table

Upvotes: 8

Views: 6575

Answers (5)

Stefan Steinegger
Stefan Steinegger

Reputation: 64628

In SqlServer 2008 there is an UPSERT command which does exactly this. I didn't try it.

Upvotes: 7

user278618
user278618

Reputation: 20232

It has the best perfomacne:

UPDATE Table1 SET (...) WHERE Column1='SomeValue'
IF @@ROWCOUNT=0
    INSERT INTO Table1 VALUES (...)

Upvotes: 12

Asad
Asad

Reputation: 21918

probably something similar with some modification would work

   IF EXISTS (SELECt * FORM carsdescriptions WHERE IDCar = @IDCar )
        UPDATE carsdescriptions 
        SET Header = @Header, Content = @Content
        WHERE IDCar = @IDCar
   ELSE
        INSERT INTO carsdescriptions (IDCar, Header, Content)
        VALUES (@IDCar, @Header, @Content)

Have a look at this article as well, will give you more insight

Upvotes: 5

Neil Knight
Neil Knight

Reputation: 48537

You'll want to do a IF EXISTS first to see if the record exists in the table. If it doesn't, INSERT the new car, else UPDATE the existing record.

Upvotes: 0

Related Questions