【问题标题】:oracle subquery insert gives ora937 and ora 979oracle 子查询插入给出 ora937 和 ora 979
【发布时间】:2019-11-27 18:59:45
【问题描述】:

当子查询具有聚合函数时,我在插入 (Oracle 12.2) 时遇到了一个奇怪的错误。子查询本身运行良好,但是当我把它放在插入语句中时,oracle 给出了错误。我还发现它与插入表中的标识列(下例中的 TESTLOGEVENT.evID)有关,因为如果我删除该列,所有插入查询都可以正常工作!

create table testitems as
   (select 1 itemid, 'x001' trackingid from dual union all select 2,'x001' from dual);

create table testlogevent(
  evType varchar(50), evDesc varchar2(1000), userID varchar2(30), evDate date,
  evID  NUMBER(8) Generated as Identity);

insert into testlogevent(evType, evDesc, userid, evDate) 
  select 'testevent', max(itemid), :UserID, sysdate
   from testitems where trackingid='x001';

>>>ORA-00937:不是单组函数

选择子查询本身可以正常工作!我试图通过在子查询中添加一个不必要的 GROUP BY 来重写它以查看它是否有效。

insert into testlogevent(evType, evDesc, userid, evDate) 
 select 'testevent', max(itemid), :UserID,sysdate
   from testitems where trackingid='x001' group by 'x001'

>>>ORA-00979:不是 GROUP BY 表达式

现在 Oracle 向我发送了 ORA-00979。然而,子查询本身工作正常。

最后,当我使用 CTE 重写(第一个插入查询)时,这次 Oracle 没有抱怨,插入工作!这是怎么回事?

insert into testlogevent(evType, evDesc, userid, evDate) 
  with x as (
    select 'testevent', max(itemid), :UserID,sysdate
      from testitems where trackingid='x001')
  select * from x;

>>>插入 1 行

【问题讨论】:

  • 如果您使用聚合函数和列,则必须在查询表达式的组中使用相同的列。这就是ORA-00937: not a single-group group function 的原因,所以...对于您的'testevent', max(itemid), :UserID, sysdate,如果 :UserID 是固定的,则您必须按部分分组为:UserID, sysdate,您不需要添加它。
  • 是的,我知道。那不是问题。阅读整个问题,然后运行示例。

标签: oracle sql-insert


【解决方案1】:

经过一番研究,似乎当有子查询插入时,Oracle 无法推断数据类型,并且与标识列相关的一些内部错误导致了这个神秘的错误消息(如果没有标识列或在 Oracle 中它工作正常11)

当我将第一个查询插入中的绑定变量:UserID 更改为: cast(:UserID as varchar2(30)) 或简单地说::UserID||'',插入有效,因为绑定变量数据类型编译为 varchar2。这似乎也是第三次插入有效的原因。

希望 Oracle 在下一次迭代中解决此问题。

【讨论】:

    猜你喜欢
    • 2020-12-30
    • 2016-10-05
    • 1970-01-01
    • 2020-11-10
    • 2016-09-25
    • 2018-11-04
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    相关资源
    最近更新 更多