小编典典

对单个表使用Merge语句

sql

是否可以对单个表使用merge语句?我想在插入之前检查一下,如果已经存在相同的一组值,那么应该更新该记录,如果没有,则应该将其插入。我已经在互联网上进行搜索,但是我得到了带有2个表的merge语句的示例。我在一张桌子上尝试,但无法获得积极的结果。我尝试检查的值将是动态的。我想在我的应用程序中使用此查询。

我试图检查(在下面的情况下,只有“主要”列),如果两列匹配,则应更新该记录,否则应将其插入。

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

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:无法在源表中获得稳定的行集

也许我做的事情完全错了。谁能帮帮我吗。


阅读 220

收藏
2021-05-16

共1个答案

小编典典

SELECT ... FROM DUALUSING子句中使用可以用数据生成一行:

SQL小提琴

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

结果

| 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) |
2021-05-16