本文介绍了在PL/pgSQL内部执行INSERT之后获取默认的序列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一张桌子.我在plpgsql中编写了一个函数,可以在此表中插入一行:
I have a table. I wrote a function in plpgsql that inserts a row into this table:
INSERT INTO simpleTalbe (name,money) values('momo',1000) ;
此表具有名为id
的serial
字段.在插入行后,我想在函数中知道新行收到的ID.
This table has serial
field called id
. I want in the function after I insert the row to know the id that the new row received.
我想使用:
select nextval('serial');
在插入之前,有更好的解决方案吗?
before the insert, is there a better solution?
推荐答案
使用 RETURNING
子句.您需要将结果保存在PL/pgSQL内部的某个地方-附加INTO
..
INSERT INTO simpleTalbe (name,money) values('momo',1000)
RETURNING id
INTO _my_id_variable;
_my_id_variable
必须使用匹配的数据类型声明.
_my_id_variable
must have been declared with a matching data type.
相关:
根据您打算如何处理它,通常使用纯SQL会有更好的解决方案.例子:
Depending on what you plan to do with it, there is often a better solution with pure SQL. Examples:
- Combining INSERT statements in a data-modifying CTE with a CASE expression
- PostgreSQL multi INSERT...RETURNING with multiple columns
这篇关于在PL/pgSQL内部执行INSERT之后获取默认的序列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!