DB2是否具有“插入或更新”声明? [英] Does DB2 have an "insert or update" statement?
问题描述
从我的代码(Java),我想确保在我的代码执行后数据库(DB2)中存在一行。
From my code (Java) I want to ensure that a row exists in the database (DB2) after my code is executed.
code> select ,如果没有返回结果,它会执行 insert
。我真的不喜欢这个代码,因为它暴露了在多线程环境中运行时的并发问题。
My code now does a select
and if no result is returned it does an insert
. I really don't like this code since it exposes me to concurrency issues when running in a multi-threaded environment.
我想做的是将这个逻辑在DB2而不是在我的Java代码。
DB2是否有一个 insert-or-update
语句?
What I would like to do is to put this logic in DB2 instead of in my Java code.
Does DB2 have an insert-or-update
statement? Or anything like it that I can use?
例如:
insertupdate into mytable values ('myid')
另一种做法可能是插入和捕获SQL代码-803主键已经存在,但我想避免,如果可能。
Another way of doing it would probably be to always do the insert and catch "SQL-code -803 primary key already exists", but I would like to avoid that if possible.
推荐答案
是的,DB2有MERGE语句,它将执行一个UPSERT(更新或插入)。
Yes, DB2 has the MERGE statement, which will do an UPSERT (update or insert).
MERGE INTO target_table USING source_table ON match-condition
{WHEN [NOT] MATCHED
THEN [UPDATE SET ...|DELETE|INSERT VALUES ....|SIGNAL ...]}
[ELSE IGNORE]
请参阅:
这篇关于DB2是否具有“插入或更新”声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!