DB2 是否具有“插入或更新"功能?陈述? [英] Does DB2 have an "insert or update" statement?
问题描述
从我的代码 (Java) 来看,我想确保在执行我的代码后数据库 (DB2) 中存在一行.
我的代码现在执行select
,如果没有返回结果,则执行insert
.我真的不喜欢这段代码,因为它让我在多线程环境中运行时遇到并发问题.
我想做的是将此逻辑放在 DB2 中而不是我的 Java 代码中.DB2 有 insert-or-update
语句吗?或者我可以使用的任何类似的东西?
例如:
insertupdate 到 mytable 值 ('myid')
另一种方法可能是始终进行插入并捕获SQL-code -803 主键已经存在",但如果可能,我想避免这种情况.
是的,DB2 有 MERGE 语句,它将执行 UPSERT(更新或插入).
MERGE INTO target_table USING source_table ON match-condition{当[不]匹配时然后[更新集...|删除|插入值....|信号...]}[其他忽略]
见:
https://www.ibm.com/developerworks/community/blogs/SQLTips4DB2LUW/entry/merge?lang=en
From my code (Java) I want to ensure that a row exists in the database (DB2) after my code is executed.
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.
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?
For example:
insertupdate into mytable values ('myid')
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.
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]
See:
https://www.ibm.com/developerworks/community/blogs/SQLTips4DB2LUW/entry/merge?lang=en
这篇关于DB2 是否具有“插入或更新"功能?陈述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!