Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 536
user278618 Avatar asked Mar 02 '10 11:03

user278618


People also ask

Is it possible to update records in a table?

The UPDATE statement is used to modify the existing records in a table.

How do you update a specific record in an existing table?

The UPDATE command in SQL is used to modify or change the existing records in a table. If we want to update a particular value, we use the WHERE clause along with the UPDATE clause. If you do not use the WHERE clause, all the rows will be affected.

Which is faster update or insert?

Is update or INSERT faster? Inserts will just about always be quicker, especially if they are either in order or if the underlying table doesn't have a clustered index.


1 Answers

It has the best perfomacne:

UPDATE Table1 SET (...) WHERE Column1='SomeValue'
IF @@ROWCOUNT=0
    INSERT INTO Table1 VALUES (...)
like image 194
user278618 Avatar answered Oct 13 '22 14:10

user278618