473,836 Members | 2,139 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Return Primary Key on INSERT statement

I am inserting a record into a table that automatically generates
unique ids (i.e. Primary Key). Is there anyway to return this id. As I
am using this on ASP.net page and I really need the ID to update the
page with the new details.

I think on mysql there is something called LAST_INSERT_ID which does
this.
Jul 20 '05 #1
10 45866
So this is an IDENTITY column? In this case, you can use SCOPE_IDENTITY( )
in SQL 2000 to return the last identity value generated on the current
connection. With SQL 7 and earlier, you can use @@IDENTITY but the value
will reflect identity values resulting from trigger inserts as well.

--
Hope this helps.

Dan Guzman
SQL Server MVP

"ree32" <re***@hotmail. com> wrote in message
news:76******** *************** ***@posting.goo gle.com...
I am inserting a record into a table that automatically generates
unique ids (i.e. Primary Key). Is there anyway to return this id. As I
am using this on ASP.net page and I really need the ID to update the
page with the new details.

I think on mysql there is something called LAST_INSERT_ID which does
this.

Jul 20 '05 #2
Can you give an example with a set of values and column names as I am
not sure how to use this statement.

"Dan Guzman" <gu******@nospa m-online.sbcgloba l.net> wrote in message news:<tD******* **********@news svr30.news.prod igy.com>...
So this is an IDENTITY column? In this case, you can use SCOPE_IDENTITY( )
in SQL 2000 to return the last identity value generated on the current
connection. With SQL 7 and earlier, you can use @@IDENTITY but the value
will reflect identity values resulting from trigger inserts as well.

--
Hope this helps.

Dan Guzman
SQL Server MVP

Jul 20 '05 #3
Here's an example that inserts a row using a proc with the generated value
returned as a single-row, single-column result

CREATE TABLE MyTable
(
MyPK int NOT NULL IDENTITY(1,1)
CONSTRAINT PK_MyTable PRIMARY KEY,
MyData int NOT NULL
)
GO

CREATE PROC MyProc
@MyData int
AS
SET NOCOUNT ON
INSERT INTO MyTable (MyData) VALUES(1)
SELECT SCOPE_IDENTITY( )
GO

EXEC MyProc @MyData = 1
GO

--
Hope this helps.

Dan Guzman
SQL Server MVP

"ree32" <re***@hotmail. com> wrote in message
news:76******** *************** ***@posting.goo gle.com...
Can you give an example with a set of values and column names as I am
not sure how to use this statement.

"Dan Guzman" <gu******@nospa m-online.sbcgloba l.net> wrote in message
news:<tD******* **********@news svr30.news.prod igy.com>...
So this is an IDENTITY column? In this case, you can use
SCOPE_IDENTITY( )
in SQL 2000 to return the last identity value generated on the current
connection. With SQL 7 and earlier, you can use @@IDENTITY but the value
will reflect identity values resulting from trigger inserts as well.

--
Hope this helps.

Dan Guzman
SQL Server MVP

Jul 20 '05 #4
"Dan Guzman" <gu******@nospa m-online.sbcgloba l.net> wrote in message news:<tD******* **********@news svr30.news.prod igy.com>...
So this is an IDENTITY column? In this case, you can use SCOPE_IDENTITY( )
in SQL 2000 to return the last identity value generated on the current
connection. With SQL 7 and earlier, you can use @@IDENTITY but the value
will reflect identity values resulting from trigger inserts as well.

--
Hope this helps.

Dan Guzman
SQL Server MVP

"ree32" <re***@hotmail. com> wrote in message
news:76******** *************** ***@posting.goo gle.com...
I am inserting a record into a table that automatically generates
unique ids (i.e. Primary Key). Is there anyway to return this id. As I
am using this on ASP.net page and I really need the ID to update the
page with the new details.

I think on mysql there is something called LAST_INSERT_ID which does
this.


Can you help me - I'm starting to think I'm going insane:

Last year, after spending several days trying to debug a few stored
procedures, we stumbled accross a bug in SQL 7 where @@IDENTITY
returned the wrong value if the table you'd just inserted into had a
self-referencing foreign key.

So I went through the stored procedure generator (code and sp
generator to create our data access layer) and added a whole load of
defensive coding in that detected that it was running on SQL 7 and
"corrected" the return value by subtracting the number of self-ref
foreign keys. This all worked fine for a while, and then stopped
working (being in error on the low side now instead) so we removed
this code, and everything has been fine since.

My only question is, does anyone know when/what corrected this bug,
since I cant seem to find it in any of the patch documents?

As a side note to the OP, who Asked how to use the @@IDENTITY, do the
following:

INSERT INTO tblBlah1 (Col1,Col2,Col3 ) VALUES (Val1,Val2,Val3 );

SELECT @@IDENTITY

(If you want to have it returned in a result set of one row/one
column) or

SET @Variable = @@IDENTITY

(If you want to store the value in a variable)
Jul 20 '05 #5
> Last year, after spending several days trying to debug a few stored
procedures, we stumbled accross a bug in SQL 7 where @@IDENTITY
returned the wrong value if the table you'd just inserted into had a
self-referencing foreign key.
This looks like the bug described in MSKB 322818
<http://support.microso ft.com/default.aspx?sc id=kb;en-us;322818>.
So I went through the stored procedure generator (code and sp
generator to create our data access layer) and added a whole load of
defensive coding in that detected that it was running on SQL 7 and
"corrected" the return value by subtracting the number of self-ref
foreign keys. This all worked fine for a while, and then stopped
working (being in error on the low side now instead) so we removed
this code, and everything has been fine since.
The work-around suggested in the article is to remove the self-referencing
foreign key(s) rather than manually adjust the value returned by @@IDENTITY.
You can use an insert trigger to enforce referential integrity instead.
This way, you won't have to change your code if/when the bug is fixed in SQL
7 or you upgrade to SQL 2000.
My only question is, does anyone know when/what corrected this bug,
since I cant seem to find it in any of the patch documents?


Particularly with hotfixes, bugs may get addressed (or introduced) without
accompanying documentation and this may happen with service packs as well.
This is why one should regression test fixes before applying to production.

I don't have a SQL 7 box handy to test this on but I can try to find out
more information. What service pack/patch level are you running?

--
Hope this helps.

Dan Guzman
SQL Server MVP
Jul 20 '05 #6
So you cannot use these SQL statements from ASP.net pages. i.e you
have to create the procedures on the SQL server?

"Dan Guzman" <gu******@nospa m-online.sbcgloba l.net> wrote in message news:<vr******* **********@news svr11.news.prod igy.com>...
Here's an example that inserts a row using a proc with the generated value
returned as a single-row, single-column result

CREATE TABLE MyTable
(
MyPK int NOT NULL IDENTITY(1,1)
CONSTRAINT PK_MyTable PRIMARY KEY,
MyData int NOT NULL
)
GO

CREATE PROC MyProc
@MyData int
AS
SET NOCOUNT ON
INSERT INTO MyTable (MyData) VALUES(1)
SELECT SCOPE_IDENTITY( )
GO

EXEC MyProc @MyData = 1
GO

--
Hope this helps.

Dan Guzman
SQL Server MVP

Jul 20 '05 #7
> So you cannot use these SQL statements from ASP.net pages. i.e you
have to create the procedures on the SQL server?
You can also run the INSERT/SELECT script directly from your code:

SET NOCOUNT ON
INSERT INTO MyTable (MyData) VALUES(1)
SELECT SCOPE_IDENTITY( )

--
Hope this helps.

Dan Guzman
SQL Server MVP

"ree32" <re***@hotmail. com> wrote in message
news:76******** *************** ***@posting.goo gle.com... So you cannot use these SQL statements from ASP.net pages. i.e you
have to create the procedures on the SQL server?

"Dan Guzman" <gu******@nospa m-online.sbcgloba l.net> wrote in message
news:<vr******* **********@news svr11.news.prod igy.com>...
Here's an example that inserts a row using a proc with the generated
value
returned as a single-row, single-column result

CREATE TABLE MyTable
(
MyPK int NOT NULL IDENTITY(1,1)
CONSTRAINT PK_MyTable PRIMARY KEY,
MyData int NOT NULL
)
GO

CREATE PROC MyProc
@MyData int
AS
SET NOCOUNT ON
INSERT INTO MyTable (MyData) VALUES(1)
SELECT SCOPE_IDENTITY( )
GO

EXEC MyProc @MyData = 1
GO

--
Hope this helps.

Dan Guzman
SQL Server MVP

Jul 20 '05 #8
"Dan Guzman" <gu******@nospa m-online.sbcgloba l.net> wrote in message news:<zu******* **********@news svr11.news.prod igy.com>...
Last year, after spending several days trying to debug a few stored
procedures, we stumbled accross a bug in SQL 7 where @@IDENTITY
returned the wrong value if the table you'd just inserted into had a
self-referencing foreign key.


This looks like the bug described in MSKB 322818
<http://support.microso ft.com/default.aspx?sc id=kb;en-us;322818>.

It was indeed this bug. I was just curious if anyone knew when/where
it was fixed, but I'm not going to worry about it too badly
(especially since I lost SA/DBO access on most of the boxes recently,
so dont have access to nearly so much information :-()
Jul 20 '05 #9
Thank you so much. IT works!!!

"Dan Guzman" <gu******@nospa m-online.sbcgloba l.net> wrote in message news:<WX******* **********@news svr11.news.prod igy.com>...
So you cannot use these SQL statements from ASP.net pages. i.e you
have to create the procedures on the SQL server?


You can also run the INSERT/SELECT script directly from your code:

SET NOCOUNT ON
INSERT INTO MyTable (MyData) VALUES(1)
SELECT SCOPE_IDENTITY( )

--
Hope this helps.

Dan Guzman
SQL Server MVP

Jul 20 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
3592
by: John Simmons | last post by:
How is it that even though I have the column "username" in my database set as a Primary key, using my PHP script to add new users to the database works without any errors even when signing up using an existing username. I have a database full of the same usernames!
2
3082
by: Paul | last post by:
I need to insert a row into a table in SQL Server 2000. The primary key for the row is an identity type, so it auto-numbers for me without needing to put in the value in the insert statement. My problem, is that after i insert a row, i need to insert another row in a different table that references the first row. To do that i need to know the primary key for the original row. How can i tell what the primary key was? In Oracle, you...
1
9894
by: Cliff | last post by:
I'm trying to do multiple insert statements. The table looks like this: CREATE TABLE $table (CNTY_CNTRY_CD char(3),ST char(2), CNTY_CNTRY_DESCR varchar(50),CNTY_CNTRY_IND char(1), HOME_CNTRY_IND char(1), CONSTRAINT cnty_key PRIMARY KEY (CNTY_CNTRY_CD, ST)) I'm using 2 fields for the primary key constraint My insert statement looks like this:
2
2915
by: Andrew Grandison | last post by:
We are converting a legacy visual foxpro system to use a SQL back-end. A number of (existing DBF) tables currently have a zero-filled primary key eg. '000255' which is just an auto-incrementing key - but always stored as a char field with leading zeros. For backward compatibility we are considering retaining this primary key and using an identity field to auto-generate the next value, then convert the new identity value into the new...
3
2242
by: Chris Gilbert | last post by:
I'm quite stuck with this: I have an import table called ReferenceMatchingImport which contains data that has been sucked from a data submission. The contents of this table have to be imported into another table ExternalReference which has various foreign keys. This is simple but one of these keys says that the value in ExternalReference.CompanyRef must be in the CompanyReference table. Of course if this is an initial import then it...
2
3281
by: John | last post by:
The ASP application inserts transaction records in transaction table with the system time as the primary key. However, it is possible to have primary key violation because the records in transaction table come from different sources. The application can show error message and the user can file a transaction again manually, but I want the application can have multiple re-tries to perform insert statement until there is no primary key...
2
8714
by: alexs | last post by:
Chaps, I'm starting to play with db2 V9.1 and am writing a stored procedure to manage accounting records from oiur RADIUS server. I've got an XML aware table with an auto increment primary key, a few sql columns and an XML column. For every XML object I'm inserting, i'd lke to have an ID attribute that has the same value as the SQL primary key that'll be created upon executing the insert.
2
45886
by: mivey4 | last post by:
Okay I have 2 tables: Table A - holds a list of new hardware serial numbers and their corresponding model (no constraints or indexes) Table B - holds a distinct list of current serial numbers and the corresponding model numbers (primary key on serial_numbers) Since Table A has no constraints duplicates may exist. Additionally, table A is actually an Excel spreadsheet that is maintained by an employee that records new hardware as...
1
3370
by: Zamdrist | last post by:
Violation of PRIMARY KEY constraint 'PK_CUSTOM2'. Cannot insert duplicate key in object 'MHGROUP.Custom2' Is there ANY other reason this violation of the primary key would happen OTHER than a trying to insert a duplicate record? This sql statement false due to the primary key violation: Insert Into MHGROUP.Custom2 Select
0
9810
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9656
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10571
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7773
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6973
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5642
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4441
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4001
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3102
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.