Oracle
 sql >> Base de données >  >> RDS >> Oracle

Utilisation de l'instruction Merge pour une seule table

Utilisez SELECT ... FROM DUAL dans le USING clause pour générer une seule ligne avec vos données :

SQL Fiddle

Configuration du schéma 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);

Requête 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 )

Requête 2 :

SELECT * FROM student

Résultats :

| 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) |