13

I've read here that the syntax looks like this:

INSERT
WHEN ([Condition]) THEN
INTO [TableName] ([ColumnName])
VALUES ([VALUES])
ELSE
INTO [TableName] ([ColumnName])
VALUES ([VALUES])
SELECT [ColumnName] FROM [TableName];

But I don't want to provide values from another table. I just want to type them, so I've got:

INSERT 
WHEN EXISTS (SELECT 1 FROM FOO WHERE NAME = 'JOE') 
THEN
INTO BAR (NAME, AGE) 
VALUES ('JOE', 50)

and this produces exception: ORA-00928: missing SELECT keyword.

I want to perform an insert if given value is found in another table.

Community
  • 1
  • 1
Kamil
  • 1,456
  • 4
  • 32
  • 50
  • I think you can only use that inside a PL/SQL procedure, not in plain SQL. The `WHEN` clause is not part of the SQL INSERT clause: https://docs.oracle.com/database/121/SQLRF/statements_9014.htm#SQLRF01604 –  Jan 25 '17 at 11:20

2 Answers2

15

Using with select works. Your query wasn't working because there is a problem with values keyword when inserting conditionally.

INSERT 
WHEN EXISTS (SELECT 1 FROM FOO WHERE NAME = 'JOE') 
THEN
INTO BAR (NAME, AGE) 
SELECT 'JOE', 50 FROM DUAL
Planky
  • 3,185
  • 3
  • 29
  • 39
hkutluay
  • 6,794
  • 2
  • 33
  • 53
4

So, I've found an indirect way here and solution for my question would be:

INSERT INTO BAR (NAME, AGE) 
SELECT 'JOE', 50
  FROM DUAL
 WHERE EXISTS (SELECT 1 FROM FOO WHERE NAME = 'JOE')

but it doesn't explain why I have to use SELECT statement in INSERT WHEN

Community
  • 1
  • 1
Kamil
  • 1,456
  • 4
  • 32
  • 50
  • I assume it is because this system relies on the `INSERT` aborting when the `SELECT` it relies on returns no results. – Nyerguds Sep 28 '17 at 12:10