我在MySQL中有一个过程,我想把它转换成Oracle过程,一切正常,但是MySQL内置函数"last_insert_id()“引发了错误。有什么解决方案吗?我可以在oracle中创建一个相同的函数吗?
SELECT LAST_INSERT_ID();发布于 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的工作方式不同,特别是当并行会话工作时。
发布于 2016-07-22 19:54:12
@krokodilko和@NicholasKrasnov告诉你如何使用returning子句。
我的示例是,如果您想获取刚刚插入的行的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;这只是代码的演示,我不会在服务器上编译它
https://stackoverflow.com/questions/38518355
复制相似问题