Retrieving Last Inserted ID

xiaoxiao2021-03-05  28

A common functionality many developers need at one time or another is to get the ID of the row they just inserted into a database. When the database's primary key is a number automatically generated by the database, it can be difficult.

DiffERENT DATABASE PACKAGES USE DIFFERENT METHODS.

Microsoft Access

With access's autonumr column, it.............................. #

Tag to ensure the returned value belongs to the row just inserted:

Insert Into Table ...

VALUES ...

SELECT MAX (ID_field) as thisid

From table

SQL Server

IF you are useless SQL Server and ITENTITY Column, You Can Perform The Insert and ID Retrieval in Just One Query:

Set nocount on

Insert Into Table ...

VALUES ...

SELECT thisid = @@ identity

Set nocount off

Nocount is set to on to reduce network traffic during the multiple queries, the set back to off. @@ identity contacts the value of the last inserted ID.

Oracle

Oracle does not have an AutoNumber or Identity column like the Microsoft databases and instead uses Sequences. A sequence must first be created for a table before it can be accessed. After you create the sequence, you'll need a query to obtain the next Value Before the actual insert.

Select Table_sequence.nextVal As thisid

From dual

INSERT INTO TABLE (ID, ...)

Values ​​(# lastid #, ...)

转载请注明原文地址:https://www.9cbs.com/read-33303.html

New Post(0)