对单个表使用Merge语句

时间:2018-05-09 11:29:53

标签: sql oracle

是否可以对单个表使用merge语句?我想在插入之前检查如果已经存在相同的值集,则应该更新该记录,如果不存在则应该插入。我在互联网上搜索过,但我得到了合并声明与2表的例子。我正在尝试一张桌子,但我无法得到积极的结果。我想要检查的值将是动态的。我想在我的应用程序中使用此查询。

我正在尝试检查(仅在以下情况下#34; Major"列)如果匹配两列,则应更新该记录,如果不匹配则应插入。

我创建了一个样本表学生。下面是查询。

create table student (sid int,name varchar(20),major varchar(10),gpa float,tutorid int, PRIMARY KEY (sid))

insert into student values(101,'Bill','CIS',3.45,102)

insert into student values(102,'Mary','CIS',3.1,null)

insert into student values(103,'Sue','Marketing',2.95,102)

insert into student values(104,'Tom','Finanace',3.5,106)

insert into student values(105,'Alex','CIS',2.75,106)

insert into student values(106,'Sam','Marketing',3.25,103)

insert into student values(107,'Joan','Finance',2.9,102)

以下是我正在使用的查询

merge into student a 
using (select name,major from student) b 
on (a.major=b.major)
when matched then
update set a.name='Rahul'
when not matched then
insert(a.SID,a.major) values(123, 'Temp') 

我收到以下错误

  

ORA-30926:无法在源表中获得一组稳定的行

也许我做的事情完全错了。任何人都可以帮助我。

1 个答案:

答案 0 :(得分:1)

SELECT ... FROM DUAL子句中使用USING生成包含数据的单行:

SQL Fiddle

Oracle 11g R2架构设置

create table student (
  sid int,
  name varchar(20),
  major varchar(10),
  gpa float,
  tutorid int,
  PRIMARY KEY (sid)
);

insert into student values(101,'Bill','CIS',3.45,102);
insert into student values(102,'Mary','CIS',3.1,null);
insert into student values(103,'Sue','Marketing',2.95,102);
insert into student values(104,'Tom','Finanace',3.5,106);
insert into student values(105,'Alex','CIS',2.75,106);
insert into student values(106,'Sam','Marketing',3.25,103);
insert into student values(107,'Joan','Finance',2.9,102);

查询1

merge into student dst
using (
  SELECT 123 AS sid,
         'Rahul' AS name,
         'Temp' AS major
  FROM   DUAL
) src
on (src.major=dst.major)
when matched then
  update set name=src.name
when not matched then
  insert(SID,name,major) values ( src.sid, src.name, src.major )

查询2

SELECT * FROM student

<强> Results

| SID |  NAME |     MAJOR |    GPA | TUTORID |
|-----|-------|-----------|--------|---------|
| 101 |  Bill |       CIS |   3.45 |     102 |
| 102 |  Mary |       CIS |    3.1 |  (null) |
| 103 |   Sue | Marketing |   2.95 |     102 |
| 104 |   Tom |  Finanace |    3.5 |     106 |
| 105 |  Alex |       CIS |   2.75 |     106 |
| 106 |   Sam | Marketing |   3.25 |     103 |
| 107 |  Joan |   Finance |    2.9 |     102 |
| 123 | Rahul |      Temp | (null) |  (null) |