【问题标题】:how to create a function in oracle for last_insert_id() in MySQL如何在 oracle 中为 MySQL 中的 last_insert_id() 创建一个函数
【发布时间】:2016-11-25 21:06:58
【问题描述】:

我在 MySQL 中有一个程序,我想将其转换为 Oracle 程序,一切正常,但 MySQL 内置函数“last_insert_id()”引发错误。有什么办法可以解决吗?我可以在 oracle 中为它创建一个函数吗?

  SELECT LAST_INSERT_ID();

【问题讨论】:

  • 在 Oracle 中搜索 returning clause 的示例,同时查看此链接 docs.oracle.com/cd/B19306_01/appdev.102/b14261/…
  • Oracle 和 MySQL 在内部工作方式不同。对 MySQL 有利的方法可能对 Oracle 不利。你想要这个功能的目的是什么?
  • 阅读 oracle 序列 docs.oracle.com/cd/B28359_01/server.111/b28310/views002.htm 我认为它对你有帮助。
  • @EvgeniyK.: 我在 MySQL 中有程序,我已将其转换为 Oracle 程序。我在 mysql 中使用了 last_insert_id() 函数,但它引发了错误。所以我想在 oracle 中创建一个函数,它的行为和返回一个类似 mysql last_insert_id() 的值。
  • @АнатолийПредеин 已经提到了序列的链接。这可能会有所帮助,但在某些情况下,由于并行会话,它的工作方式与 MySQl 中的不同。

标签: mysql sql oracle plsql


【解决方案1】:

您不能在 Oracle 中执行与 MySQL 中完全相同的功能,如果我错了,请纠正我。

在 MySQL 文档中查看此注释(http://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_last-insert-id)

对于改变值的存储函数和触发器,值是 当函数或触发器结束时恢复,所以下面的语句 不会看到更改的值。

重要

如果您使用单个 INSERT 语句插入多行, LAST_INSERT_ID() 返回为第一个插入生成的值 仅行。这样做的原因是为了让重现成为可能 很容易对其他服务器执行相同的 INSERT 语句。

在 Oracle 中,自动增量列从 12c 开始工作,它们基于序列。如果有人调用 sequence.NextVal,那么所有会话将只看到更改的序列值。在 MySQL 中的行为是不同的(再次查看重要说明)

Oracle 和 MySQL 的工作方式不同,尤其是在并行会话工作时。

【讨论】:

    【解决方案2】:

    @krokodilko 和@NicholasKrasnov 告诉你如何使用返回子句。

    我的例子,如果你想获取刚刚插入的行的 ID:

    declare
     l_id number;
    begin
    -- ONE ROW INSERT
    l_id := someseq.nextval;
    begin
      insert into temp(id) values(l_id);
     -- if insert fail then variable must be null
     exception when others then l_id := null ;
    end;
    
    if l_id is not null then 
      -- do what you want RETURN this, or use for other statements
      null;
      -- here you have just now inserted ID in variable l_id
    end if;
    
    -- MULTIPLE INSERT
    
    for some_data in (select * from some_joined_tables) loop
    
      l_id := someseq.nextval;
    
      begin
        insert into temp(id) values(l_id);
       exception when others then l_id := null ;
      end;
    
      if l_id is not null then 
        -- do what you want RETURN this, or use for other statements
        -- here you have just now inserted ID in variable l_id
      end if;
    
    end loop;
    
    -- HERE (after loop) YOU CAN RETURN LAST INSERTED VALUE of current transaction in variable l_id
    
    end;
    

    这只是代码的演示,我没有在服务器上编译它

    【讨论】:

      猜你喜欢
      • 2020-07-30
      • 1970-01-01
      • 1970-01-01
      • 2012-11-28
      • 2021-08-20
      • 1970-01-01
      • 2020-12-24
      • 2021-04-10
      • 2012-05-27
      相关资源
      最近更新 更多