I was under the impression that it could not, but then I ran across these 2 examples (using Oracle XE and SQL Developer):

Example 1 - executes without error

insert into regions (region_id, region_name)
values ((select max(region_id)+1 from regions), 'Great Britain');

Example 2 - returns error (shown below)

insert into regions (region_id, region_name)
values (select region_id, region_name from regions);

Error:

Error starting at line 1 in command:
insert into regions (region_id, region_name)
values (select region_id, region_name from regions)
Error at Command Line:2 Column:9
Error report:
SQL Error: ORA-00936: missing expression
00936. 00000 -  "missing expression"
*Cause:    
*Action:

So, it appears that there is more to it. Can anyone provide an explanation of under what conditions it is/isn't ok to include subqueries with the VALUES keyword?

有帮助吗?

解决方案

You need to insert subqueries in parentheses. The opening paren for values doesn't count. It is the start of a list, not a subquery. You can include subqueries in the VALUES clause when they return one row and one column.

Instead, though, you can use this syntax:

insert into regions (region_id, region_name)
    select max(region_id) + 1, 'Great Britain'
    from regions;

Better yet would be to assign a sequence to the region_id (identity or auto-increment column in other databases) so it is assigned automatically. Then you would just do:

insert into regions (region_name)
    select 'Great Britain'
    from dual;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top