【问题标题】:Can a subquery be used with the VALUES keyword?子查询可以与 VALUES 关键字一起使用吗?
【发布时间】:2014-02-08 20:26:11
【问题描述】:

我的印象是它不能,但后来我遇到了这两个示例(使用 Oracle XE 和 SQL Developer):

示例 1 - 执行没有错误

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

示例 2 - 返回错误(如下所示)

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

错误:

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:

因此,它似乎还有更多内容。谁能解释在什么情况下可以/不可以使用VALUES 关键字包含子查询?

【问题讨论】:

  • 我有一本 Oracle 书说...子查询可用于选择要插入的行,但不能在 INSERT 语句的 VALUES 子句中选择...是真的。但是,正如您在示例 1 中指出的那样,这不是真的。你可以在 values 子句中使用 subqeuries,就像上面展示的那样。

标签: sql subquery oracle-xe dml


【解决方案1】:

您需要在括号中插入子查询。 values 的开头括号不计算在内。它是列表的开始,而不是子查询。您可以在 VALUES 子句返回一行和一列时包含子查询。

不过,您可以使用以下语法:

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

最好将序列分配给region_id(其他数据库中的标识或自动增量列),以便自动分配。然后你会这样做:

insert into regions (region_name)
    select 'Great Britain'
    from dual;

【讨论】:

  • 知道了 - 所以,VALUES 子句中只允许使用标量子查询?
  • @JeffLevine 。 . .是的,这是一个很好的说法。我避免使用VALUES 子句仅仅是因为insert . . . select 做了它所做的一切,还有更多。
猜你喜欢
  • 2017-03-05
  • 1970-01-01
  • 2012-03-02
  • 2015-11-07
  • 2015-05-10
  • 1970-01-01
  • 2021-10-11
  • 2015-09-11
  • 1970-01-01
相关资源
最近更新 更多