Insert or update if record is in table

2019-04-06 21:04发布

问题:

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:

It has the best perfomacne:

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


回答2:

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



回答3:

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

  • SQL Server: Best way to Update row if exists, Insert if not


回答4:

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.



回答5:

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