[英]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
我不能使用唯一键,因此不能使用ON复制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 仅供参考:数据库是Mysql
You could work with a temporary 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. 如果并发可能是一个问题,请确保在
TRANSACTION ISOLATION LEVEL REPEATABLE READ
运行。
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.
注意:事务非常好,但在使用多个查询进行插入/更新时使用IF EXISTS并不好。
你可以使用EXISTS或检查sub select的cound,如果它> 0,知道该行是否已经存在
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.