Whats the standard way of getting the last insert id?

后端 未结 4 1278
刺人心
刺人心 2021-01-05 05:32

What\'s the sql standard to get the last inserted id? If there is such a thing.

mysql: LAST_INSERT_ID()
postgresql: ... RETURNING f_id
mssql: SCOPE_IDENTIT

4条回答
  •  情歌与酒
    2021-01-05 05:51

    See this answer Retrieve inserted row ID in SQL

    In short, there is no cross database way to do this, except MAX(ID) - but that is not a guaranteed result and has many many pitfalls, e.g.

    • other inserts can come between last insert and max query
    • cannot be used with high transaction tables (max will issue a read lock, rdbms-specific methods do not read from any table)

    The ANSI standard that relates to identity/autonumber/auto_increment/sequences first appeared in SQL:2003 awaiting implementation by all major RDBMS. It will most likely resemble Oracle/PostgreSQL sequences.

    The SQL:2003 standard makes minor modifications to all parts of SQL:1999 (also known as SQL3), and officially introduces a few new features such as:

    - the sequence generator, which allows standardized sequences

    Another change in SQL:2003 is the OUTPUT USING CLAUSE but there is very little information about it. Sybase and SQL Server have done different things with it, so it is unclear as yet how it will pan out. SQL Server implements it as

    INSERT INTO TBL(..)
    OUTPUT inserted.identity_col
    INTO @sometablevar
    VALUES(..)
    

提交回复
热议问题