SAMPLE: Ident.exe Retrieves @@IDENTITY From ODBC InsertsID: Q185821
|
When inserting values into a table with an identity column, SQL Server
automatically generates the next identifier based on the last used identity
value. You might want to retrieve this automatically generated identity
value immediately after an insert.
The Ident.exe sample demonstrates how to retrieve the automatic @@IDENTITY
value from an insert into a Microsoft SQL Server database. The sample
consists of a simple MFC AppWizard project based on the CRecordset class.
The project was modified slightly to allow inserts into the table and to
retrieve the automatically generated identity value for the insert. It uses
the pubs data source name (DSN), although any DSN will work, and a table
called tblIdentity.
The following file is available for download from the Microsoft Software Library:
~ Ident.exeRelease Date: May-19-1998
Q119591 How to Obtain Microsoft Support Files from Online ServicesIdent.exe includes an algorithm and sample code that illustrate how to retrieve the identity value from a SQL Server database. You can use this method for multiple processes or threads doing simultaneous inserts into the same table. (Note that threads cannot share connections.)
CREATE TABLE insertTbl (myAuto int IDENTITY (1, 1) NOT NULL ,
lname varchar (15) NOT NULL ,
fname varchar (15) NOT NULL )
Because names are not unique, the code uses the identity property of SQL
Server to automatically generate a unique key.
CREATE TRIGGER trgAudit ON insertTbl FOR INSERT
AS
INSERT INTO tblIdentity VALUES (@@IDENTITY, 'insertTbl', @@SPID)
Immediately after an insertion into tblIdentity, the trigger fires and
stores:
insert into insertTbl (lname,fname) VALUES ('Smith','Joe')
select * from tblIdentity
The Results tab should look similar to the following:
iID strTable SPID
----------- --------------- -----------
5 insertTbl 11
(1 row(s) affected)
The iID and SPID values you see will probably not be 5 and 11. The
tblIdentity values verify that the Master.sql script was successful.
For more information, please see the following article in the Microsoft Knowledge Base:
Q163446 PRB: Guarantee @@IDENTITY Value on a Per Table Basis
Additional query words: kbSQLServ kbSQL kbDriver kbODBC kbMFC kbVC500 kbDSupport kbdse
Keywords : kbfile kbsample
Version : WINDOWS:3.5,3.6; WINNT:5.0
Platform : WINDOWS winnt
Issue type : kbhowto
Last Reviewed: July 27, 1999