一种方法是在插入之前先用函数 nextval() 从序列对象里检索出下一个 SERIAL 值,然后再用此值精确地插入。使用例子里的例表,可用伪码这样描述:
new_id = execute("SELECT nextval('person_id_seq')"); execute("INSERT INTO person (id, name) VALUES (new_id, 'Blaise Pascal')");
这样还能在其他查询中使用存放在 new_id 里的新值(例如,作为参照 person 表的外键)。 注意自动创建的 SEQUENCE 对象的名称将会是 <table>_<serialcolumn>_seq, 这里 table 和 serialcolumn 分别是你的表的名称和你的 SERIAL 字段的名称。
类似的,在 SERIAL 对象缺省插入后你可以用函数 currval() 检索刚赋值的 SERIAL 值,例如:
execute("INSERT INTO person (name) VALUES ('Blaise Pascal')"); new_id = execute("SELECT currval('person_id_seq')");<script type=text/javascript> </script> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type=text/javascript> </script>
<script type="text/javascript"> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>