DB2 是否具有“插入或更新"功能?陈述? [英] Does DB2 have an "insert or update" statement?

查看:65
本文介绍了DB2 是否具有“插入或更新"功能?陈述?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我的代码 (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{当[不]匹配时然后[更新集...|删除|插入值....|信号...]}[其他忽略]

见:

http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.admin.doc/doc/r0010873.htm

https://www.ibm.com/support/knowledgecenter/en/SS6NHC/com.ibm.swg.im.dashdb.sql.ref.doc/doc/r0010873.html>

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:

http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.admin.doc/doc/r0010873.htm

https://www.ibm.com/support/knowledgecenter/en/SS6NHC/com.ibm.swg.im.dashdb.sql.ref.doc/doc/r0010873.html

https://www.ibm.com/developerworks/community/blogs/SQLTips4DB2LUW/entry/merge?lang=en

这篇关于DB2 是否具有“插入或更新"功能?陈述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆