我有一个简单的查询,但只有一部分让我困惑:
我有以下算法:
merge into table_1 table_2
on table_1.val1 = table_2.val1
when matched and table_1.val2 = table_2.val2
then merge
when matched and table_1.val2 != table_2.val2
then delete and insert ( I AM NOT SURE NOW TO DO THIS)
when not matched
then insert;
你可以帮我解决删除并插入或告诉我一个方法吗?
答案 0 :(得分:3)
您不能在WHEN MATCHED THEN UPDATE子句中插入。你只能在这里删除。如果你可以更新,为什么还需要删除然后插入?像这样:
merge into table_1
using table_2 on (table_1.val1 = table_2.val1)
when matched then
update set table_1.val3 =
case when table_1.val2 = table_2.val2
then table_1.val3
else table_2.val3 end
when not matched then insert ...
从下面的评论中我想你需要这样的东西:
1)没有引用table_1的外键
2)禁用table_1中的主键val2
3)更新table_1设置val2 = null;
4)运行合并
5)从table_1删除val2为空;
6)启用table_1中的主键