简体   繁体   中英

Execute update if row exists else do insert

I have to update a number of rows to a table, if the updating row is not existing in the table I need to insert that row. I cannot use unique key, so no use with ON duplicate KEY UPDATE

I have to achieve something like this

DECLARE count DOUBLE;
SELECT count(uid) 
INTO   count 
FROM   Table 
WHERE  column1  ='xxxxx'
 AND   column2='xxxxx';

IF (count=0)
THEN
    --peform insert
ELSE
    --perform update
END IF

This is for a high performance application.Any ideas? Code level or Query level

FYI : Database is Mysql

You could work with a temporary table.

  1. Put your data into a temporary table
  2. Do an update of the "other" table via a JOIN
  3. Delete the matching data from the temp table
  4. Insert the remaining stuff from the temp table into the main table.

This will be faster than doing it record by record if you have loads of data.

That's the store procedure we use, could possibly work for you as well.

if not exists (select 1 from Table  where column1  ='xxxxx' AND   column2='xxxxx')
        insert into Table ( column1,column2)
        values ( @xxxx,xxxxx)
else 
    update Table
UPDATE <TABLE>
SET COLUMN1 = 'xxxx', COLUMN2 ...
WHERE COLUMN1 = ... AND COLUMN2 ...

IF @@ROWCOUNT = 0
   INSERT INTO <TABLE> (COLUMN1, ...)
   VALUES ('xxxx', ...)

Make sure you run in TRANSACTION ISOLATION LEVEL REPEATABLE READ if concurrency could be an issue.

BEGIN TRAN
IF EXISTS ( SELECT  *
        FROM Table WITH ( UPDLOCK, SERIALIZABLE )
        WHERE CONDITION) 
BEGIN
    UPDATE Table SET SOMETHING WHERE CONDITION
END
ELSE 
BEGIN
    INSERT INTO Table(Field1,....) VALUES  (Value1,..... )
END
COMMIT TRAN

NOTE: Transaction are very good but using IF EXISTS is not good in case of Insertion/Updation with mulitple queries.

你可以使用EXISTS或检查sub select的cound,如果它> 0,知道该行是否已经存在

You may find useful REPLACE statement. Its syntax described here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM