2011-05-02 116 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值。