我有3张桌子,T1 T2和T3。 每个表都有相同的列,除了T3有一个额外的"代码"列。
我的逻辑如下:
- 我必须搜索T1中也包含在T2中的任何行。
- 对于每个找到的行,我必须在T3中移动它,这意味着将其从T1中删除并将其创建为T3,代码为100。
我知道oracle允许从select语句中插入...,在这种情况下,我有这个:
insert into T3 (100,c1,c2,c3)
select c1,c2,c3 from T1 where exists (select null from T2 where
c1=T1.c1 and c2=T1.c2 and c3=T1.c3);
这解决了选择/插入问题,但是可以在不添加select语句的情况下从T1添加删除吗?
答案 0 :(得分:2)
您可能正在寻找MERGE
此语句是组合多个操作的便捷方式。它 允许您避免使用多个INSERT,UPDATE和DELETE DML语句。
示例强>
此示例包含所有3个DML操作(INSERT,UPDATE和DELETE)
select stuff((select ',' +Convert(varchar(50),id)
from TestAhmet
for xml path ('')
), 1, 1, '') as users
回答OP
MERGE INTO bonuses D
USING (SELECT employee_id, salary, department_id FROM employees
WHERE department_id = 80) S
ON (D.employee_id = S.employee_id)
WHEN MATCHED THEN UPDATE SET D.bonus = D.bonus + S.salary*.01
DELETE WHERE (S.salary > 8000)
WHEN NOT MATCHED THEN INSERT (D.employee_id, D.bonus)
VALUES (S.employee_id, S.salary*0.1)
WHERE (S.salary <= 8000);
我已经测试并且工作正常。
答案 1 :(得分:0)
使用循环可能很有用:
BEGIN
FOR rec IN
(SELECT c1, c2, c3 from T1 WHERE EXISTS (SELECT NULL FROM T2 WHERE
c1 = T1.c1 AND c2 = T1.c2 AND c3 = T1.c3))
LOOP
INSERT INTO T3 (100, rec.c1, rec.c2, rec.c3);
DELETE FROM T1 WHERE T1.c1 = rec.c1
and T1.c2 = rec.c2
AND T1.c3 = rec.c3;
END LOOP;
END;