使用Oracle中的merge语句删除数据

时间:2015-02-03 13:35:47

标签: plsql

如何使用oracle使用merge删除数据... 我使用以下代码:

Merge 
into 
target_table
using 
source_tablle 
on (...)
when matched 
then delete

但是我在最后一行收到错误“缺少关键字”

1 个答案:

答案 0 :(得分:1)

您最后的MERGE错过了UPDATE条款 让我们看一下示例MERGE

CREATE TABLE employee (
employee_id NUMBER(5),
first_name  VARCHAR2(20),
last_name   VARCHAR2(20),
dept_no     NUMBER(2),
salary      NUMBER(10));

INSERT INTO employee VALUES (1, 'Dan', 'Morgan', 10, 100000);
INSERT INTO employee VALUES (2, 'Helen', 'Lofstrom', 20, 100000);
INSERT INTO employee VALUES (3, 'Akiko', 'Toyota', 20, 50000);
INSERT INTO employee VALUES (4, 'Jackie', 'Stough', 20, 40000);
INSERT INTO employee VALUES (5, 'Richard', 'Foote', 20, 70000);
INSERT INTO employee VALUES (6, 'Joe', 'Johnson', 20, 30000);
INSERT INTO employee VALUES (7, 'Clark', 'Urling', 20, 90000);

CREATE TABLE bonuses (
employee_id NUMBER, bonus NUMBER DEFAULT 100);

INSERT INTO bonuses (employee_id) VALUES (1);
INSERT INTO bonuses (employee_id) VALUES (2);
INSERT INTO bonuses (employee_id) VALUES (4);
INSERT INTO bonuses (employee_id) VALUES (6);
INSERT INTO bonuses (employee_id) VALUES (7);
COMMIT;

现在我们有一个示例数据结构让我们进行一些合并:

MERGE INTO bonuses b
USING (
  SELECT employee_id, salary, dept_no
  FROM employee
  WHERE dept_no =20) e
ON (b.employee_id = e.employee_id)
WHEN MATCHED THEN
  UPDATE SET b.bonus = e.salary * 0.1
  DELETE WHERE (e.salary < 40000)
;

因此,使用MERGE命令merge_update_clause语法:
MERGE INTO(表/视图)
USING(表/视图)
ON(条件)
WHEN MATCHED THEN
UPDATE SET(column..expression)
DELETE WHERE(条件)

我想我所暗示的是你错过了UPDATE SET条款以及DELETE条件。我建议您使用MERGE语法进行跟进 **编辑:** SQLFiddle返回so here you go