首页 > 解决方案 > 我想根据匹配键更新数据库中 2 个表的记录

问题描述

我有 2 个表,源和目标如下,

资源

Key | Source_ID | Target_ID | Source_Data
-----------------------------------------
1     s1          null        some_source_data
2     s2          null        some_source_data

目标

Key | Source_ID | Target_ID | Target_Data
-------------------------------------------
1     null        t1          some_target_data
2     null        t2          some_target_data

最初源表有现有记录,并新插入记录到目标表现在我的要求是根据键匹配更新目标表中的 Target_ID 和源表中的 Source_ID 的记录,截至目前我在 java 上通过加入这些两个表使用 Key Column 并将结果保存在 Result Set 中并一个一个地对两个表执行更新查询,它在数据数量较少的情况下工作得很好,但在数据量很大的情况下 Java 执行需要大量每个表上 200000 条记录的时间需要 2 小时才能完成操作,现在我希望它移出 java 并仅像触发器或 PL/SQL 一样在 SQL 中执行,在目标表中插入记录时,这些触发器或脚本应该自动运行并完成正在做 java 的工作,需要您的帮助/建议如何实现这一点,我正在使用 DB2 数据库

标签: javasqlplsqltriggersdb2

解决方案


So what you need to do is to create a trigger on your source_Table that updates target_id in your target_table.

That should do the trick:

CREATE TRIGGER update_targettable
AFTER UPDATE ON source_table
FOR EACH ROW 
BEGIN
UPDATE target_table SET target_id = :NEW.source_id WHERE key = :NEW.key
END;

So let´s say you make an update on your Source Table.

UPDATE SOURCE_TABLE SET SOURCE_ID = s1 where key = 1;

This will automatically set your target_table.target_id to the same value as in source_table.source_id where the keys are matching.

I hope that is what you need. Otherwise please specify your question.

I recommend reading.


推荐阅读