0

我有一张桌子。我在 plpgsql 中编写了一个函数,将一行插入到该表中:

INSERT INTO simpleTalbe (name,money) values('momo',1000) ;

该表具有serial名为 的字段id。我想在插入行后的函数中知道新行收到的 id。

我想用:

select nextval('serial');

在插入之前,有没有更好的解决方案?

4

2 回答 2

3

使用RETURNING从句。您需要将结果保存在 PL/pgSQL 中的某处 - 并附加INTO..

INSERT INTO simpleTalbe (name,money) values('momo',1000)
RETURNING id
INTO _my_id_variable;

_my_id_variable必须使用匹配的数据类型声明。

有关的:

根据您打算用它做什么,通常有一个更好的纯 SQL 解决方案。例子:

于 2015-11-20T23:20:35.627 回答
1

select nextval('serial'); would not do what you want; nextval() actually increments the sequence, and then the INSERT would increment it again. (Also, 'serial' is not the name of the sequence your serial column uses.)

@Erwin's answer (INSERT ... RETURNING) is the best answer, as the syntax was introduced specifically for this situation, but you could also do a

SELECT currval('simpletalbe_id_seq') INTO ...

any time after your INSERT to retrieve the current value of the sequence. (Note the sequence name format tablename_columnname_seq for the automatically-defined sequence backing the serial column.)

于 2015-11-20T23:31:41.900 回答