首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在oracle中为MySQL中的last_insert_id()创建函数

如何在oracle中为MySQL中的last_insert_id()创建函数
EN

Stack Overflow用户
提问于 2016-07-22 12:48:19
回答 2查看 1.6K关注 0票数 1

我在MySQL中有一个过程,我想把它转换成Oracle过程,一切正常,但是MySQL内置函数"last_insert_id()“引发了错误。有什么解决方案吗?我可以在oracle中创建一个相同的函数吗?

代码语言:javascript
运行
复制
  SELECT LAST_INSERT_ID();
EN

回答 2

Stack Overflow用户

发布于 2016-07-22 15:23:52

你不能在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,那么所有会话将只看到更改后的sequence值。在MySQL中的行为是不同的(再看一遍重要的注意事项)

Oracle和MySQL的工作方式不同,特别是当并行会话工作时。

票数 0
EN

Stack Overflow用户

发布于 2016-07-22 19:54:12

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

我的示例是,如果您想获取刚刚插入的行的ID:

代码语言:javascript
运行
复制
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;

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38518355

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档