views:

111

answers:

5

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

+1  A: 

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

Asad Butt
I know update :)
A: 

First: http://www.w3schools.com/sql/default.asp

Second: http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx

Lars Mæhlum
This is definitively not a very specific answer to the question.
Stefan Steinegger
Very true. As i reread the question, I see that I _really_ misunderstood it..
Lars Mæhlum
+3  A: 

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.

Ardman
+3  A: 

It has the best perfomacne:

UPDATE Table1 SET (...) WHERE Column1='SomeValue'
IF @@ROWCOUNT=0
    INSERT INTO Table1 VALUES (...)
+1, I like this.
Stefan Steinegger
+2  A: 

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

Stefan Steinegger
+1 for new feature finally good reason for migration on 2008
adopilot