473,387 Members | 1,903 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

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 45819
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.google.c om...
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******@nospam-online.sbcglobal.net> wrote in message news:<tD*****************@newssvr30.news.prodigy.c om>...
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.google.c om...
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******@nospam-online.sbcglobal.net> wrote in message
news:<tD*****************@newssvr30.news.prodigy.c om>...
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******@nospam-online.sbcglobal.net> wrote in message news:<tD*****************@newssvr30.news.prodigy.c om>...
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.google.c om...
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.microsoft.com/default.aspx?scid=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******@nospam-online.sbcglobal.net> wrote in message news:<vr*****************@newssvr11.news.prodigy.c om>...
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.google.c om... 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******@nospam-online.sbcglobal.net> wrote in message
news:<vr*****************@newssvr11.news.prodigy.c om>...
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******@nospam-online.sbcglobal.net> wrote in message news:<zu*****************@newssvr11.news.prodigy.c om>...
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.microsoft.com/default.aspx?scid=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******@nospam-online.sbcglobal.net> wrote in message news:<WX*****************@newssvr11.news.prodigy.c om>...
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
I'm glad I was able to help you out.

--
Dan Guzman
SQL Server MVP

"ree32" <re***@hotmail.com> wrote in message
news:76**************************@posting.google.c om...
Thank you so much. IT works!!!

"Dan Guzman" <gu******@nospam-online.sbcglobal.net> wrote in message
news:<WX*****************@newssvr11.news.prodigy.c om>...
> 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 #11

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

Similar topics

6
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...
2
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. ...
1
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),...
2
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...
3
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...
2
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...
2
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...
2
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...
1
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...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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,...
0
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...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.