Retrieving Last Inserted ID

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 AutoNumber columns, the only method to use is to use two queries, one to insert the row and another to pull the maximum value of the primary key in that table. Both queries should be within a 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 using SQL Server and its Identity 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, then set back to OFF when complete. @@Identity contains the value of the last inserted ID.

Oracle
Oracle doesn't 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. You can use that value in the insert itself. So unlike Access and SQL Server, you must specify the value of the ID in the insert query.




SELECT Table_Sequence.NextVal AS ThisID
FROM Dual



INSERT INTO Table (ID, ...)
valueS (#LastID#, ...)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值