How to Get the Primary ID after a SQL Insert

From Hostek.com Wiki
Revision as of 20:21, 5 May 2014 by Briana (Talk | contribs) (Created page with "__FORCETOC__ Often times you need to get the ID of a new record that was just added to a database. This wiki gives you the solution on How to Get the Primary ID after a SQL ...")

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search


Often times you need to get the ID of a new record that was just added to a database. This wiki gives you the solution on How to Get the Primary ID after a SQL insert.

ColdFusion - How to Get the Primary ID after a SQL Insert

<CFQUERY NAME="MyInsert" DATASOURCE="#MyDataSource#">
SET NOCOUNT ON
INSERT INTO MyTable (name,email)
VALUES ('#fname#','#email#')
SELECT @@identity AS MyNewID
SET NOCOUNT OFF
</CFQUERY>
<CFOUTPUT>#MyInsert.MyNewID#</CFOUTPUT>

Note: Notice the NOCOUNT lines. This gives us data integrity so that we get the proper ID, even if another record was added during this time.