SQL - Inserting a row and returning primary key

前端 未结 8 1117
南笙
南笙 2020-12-01 18:07

I have a little witty problem. Say, I inserted a row with some data in a table where a primary key is present. How would one \"SELECT\" the primary key of the row one just i

相关标签:
8条回答
  • 2020-12-01 18:11
    select MAX(id_column) from table
    

    That, in theory, should return you that last inserted id. If it's a busy database with many inserts going on it may not get the one you just did but another.

    Anyhow, an alternative to other methods.

    0 讨论(0)
  • 2020-12-01 18:15

    If you need to retrieve the new index in MS SQL when there are triggers on the table then you have to use a little workaround. A simple OUTPUT will not work. You have to do something like this (in VB.NET):

    DECLARE @newKeyTbl TABLE (newKey INT);
    INSERT INTO myDbName(myFieldName) OUTPUT INSERTED.myKeyName INTO @newKeyTbl VALUES('myValue'); " & _
    SELECT newKey FROM @newKeyTbl;"
    

    If using .NET, then the return value from this query can be directly cast to an integer (you have to call "ExecuteScalar" on the .NET SqlCommand to get the return).

    0 讨论(0)
  • 2020-12-01 18:19

    For SQL Server 2005 and up, and regardless of what type your primary key is, you could always use the OUTPUT clause to return the values inserted:

    INSERT INTO dbo.YourTable(col1, col2, ...., colN)
    OUTPUT Inserted.PrimaryKey
    VALUES(val1, val2, ....., valN)
    
    0 讨论(0)
  • 2020-12-01 18:20

    For Postgresql:

    SELECT CURRVAL(pg_get_serial_sequence('schema.table','id'))
    

    Source: https://stackoverflow.com/questions/2944297/postgresql-function-for-last-inserted-id

    0 讨论(0)
  • 2020-12-01 18:20

    For SQLite:

    SELECT [Column_1],  [Column_2],...  [Column_n]
    FROM [YourTable]
    WHERE rowid = (SELECT last_insert_rowid())
    

    whereas:

    • Column_1, Column_2,... Column_n: are the primary key of YourTable.

    If you'd created YourTable with primary key replaced rowid (i.e. one column pk defined as INTEGER PRIMARY KEY) you just use:

    SELECT last_insert_rowid()
    

    Which is a common case.
    Finally, this wont work for WITHOUT_ROWID tables.

    Please Check:

    https://www.sqlite.org/lang_corefunc.html#last_insert_rowid

    0 讨论(0)
  • 2020-12-01 18:21

    For MySQL, use LAST_INSERT_ID()

    http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

    You should also be able to start a transaction, insert the row, and select the row using some field that has a unique value that you just inserted, like a timestamp or guid. This should work in pretty much any RDBMS that supports transactions, as long as you have a good unique field to select the row with.

    0 讨论(0)
提交回复
热议问题