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 :
- delete from carsdescriptions where idcar=@idcar
- insert into cardescriptions (, @Header,@Content,@IDCar)
the record must be updated if is in table, and inserted if doesn't exist in table
It has the best perfomacne:
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
IF @@ROWCOUNT=0
INSERT INTO Table1 VALUES (...)
In SqlServer 2008 there is an UPSERT command which does exactly this. I didn't try it.
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
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.
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