2011-05-02 57 views

回答

7

看看RETURNING clause

INSERT INTO table [ (column [, ...]) ] 
    { DEFAULT VALUES | VALUES ({ expression | DEFAULT } [, ...]) [, ...] | query } 
    [ RETURNING * | output_expression [ AS output_name ] [, ...] ] 

插入一行到表distributors,返回由DEFAULT子句中生成的序列号:

INSERT INTO distributors (did, dname) VALUES (DEFAULT, 'XYZ Widgets') 
    RETURNING did; 
+0

谢谢。你节省了我的一天。 – Zeck 2011-05-02 06:29:14

1

RETURNING如果你正在运行V8.2 +的伟大工程。否则,你可能会使用currval()doc here)。

0

看起来像Sentinel's suggestionPostgreSQL RETURNING clause是最容易使用的东西。

您可能还对OpenERP的ORM类如何管理新记录的id值感兴趣。下面是来自orm.create()方法的一个片段:

# Try-except added to filter the creation of those records whose filds are readonly. 
    # Example : any dashboard which has all the fields readonly.(due to Views(database views)) 
    try: 
     cr.execute("SELECT nextval('"+self._sequence+"')") 
    except: 
     raise except_orm(_('UserError'), 
        _('You cannot perform this operation. New Record Creation is not allowed for this object as this object is for reporting purpose.')) 
    id_new = cr.fetchone()[0] 

它使用了序列为每个表生成值新的ID。序列的名称默认为表的名称加'_id_seq',您可以在orm.__init__() method中看到。

我不知道你在努力完成什么,但是你可能会发现使用the orm class为你创建记录并让它处理细节更容易。例如,the create method返回新记录的id值。

相关问题