I have a tables Cars and CarDescriptions
我有一张桌子汽车和CarDescriptions
cars: IDCar(int, PK, autoincrement) carsDesciptions(IDDescription, Header(nvarchar),Content(nvarchar),idCar(int,FK)
汽车: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 ??
1.如何在数据库中保存已更改的Car和描述?
I have ID of Car, and I have ID's of Descriptions
我有车的ID,我有ID的描述
Class CarDescirption doesn't have any pool like IsChanged, so
类CarDescirption没有像IsChanged这样的任何池,所以
I don't wanna do something like :
我不想做类似的事情:
- delete from carsdescriptions where idcar=@idcar
- insert into cardescriptions (, @Header,@Content,@IDCar)
从iddes = @ idcar的carsdescriptions中删除
插入cardescriptions(,@ Header,@ Content,@ IDCar)
the record must be updated if is in table, and inserted if doesn't exist in table
如果在表中,则必须更新记录,如果表中不存在则必须插入
5 个解决方案
#1
12
It has the best perfomacne:
它具有最好的性能:
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
IF @@ROWCOUNT=0
INSERT INTO Table1 VALUES (...)
#2
7
In SqlServer 2008 there is an UPSERT command which does exactly this. I didn't try it.
在SqlServer 2008中有一个UPSERT命令就是这样做的。我没试过。
#3
5
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
SQL Server:如果存在则更新行的最佳方法,如果不存在则插入
#4
0
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.
您首先要进行IF EXISTS以查看表中是否存在记录。如果没有,请插入新车,否则更新现有记录。
#5
#1
12
It has the best perfomacne:
它具有最好的性能:
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
IF @@ROWCOUNT=0
INSERT INTO Table1 VALUES (...)
#2
7
In SqlServer 2008 there is an UPSERT command which does exactly this. I didn't try it.
在SqlServer 2008中有一个UPSERT命令就是这样做的。我没试过。
#3
5
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
SQL Server:如果存在则更新行的最佳方法,如果不存在则插入
#4
0
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.
您首先要进行IF EXISTS以查看表中是否存在记录。如果没有,请插入新车,否则更新现有记录。