微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PostgreSQL使用存储过程为插入的数据自动生成ID

数据库中经常需要插入纪录,为每条记录维持一个ID,在Postgresql中的方法为:
在表中插入ID
产生一个序列发生器!!
CREATE SEQUENCE serial START 101;
使用序列操作函数
Table9.38.Sequence Functions
Function
Return Type
Description
currval(regclass)
bigint
Return value most recently obtained with nextval for specified sequence
lastval()
bigint
Return value most recently obtained with nextval for any sequence
nextval(regclass)
bigint
Advance sequence and return new value
setval(regclass,bigint)
bigint
Set sequence's current value
setval(regclass,bigint,boolean)
bigint
Set sequence's current value and is_called flag
以下为实例程序
nextval方法的参数可以直接用序列发生器的名称字符串
一个bigint变量接受产生的序列号
REATE OR REPLACE FUNCTION add_student("name" text,age integer)
RETURNS bigint AS
$BODY$DECLARE
s_no bigint;
BEGIN
s_no := nextval('serial');
insert into students values (s_no,$1,$2);
return s_no;
END;$BODY$

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐