473,587 Members | 2,229 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Get next unique ID from a table before insert @@identity / Sequence

How do I get the next int value for a column before I do an insert in
MY SQL Server 2000? I'm currently using Oracle sequence and doing
something like:

select seq.nextval from dual;

Then I do my insert into 3 different table all using the same uniqueID.

I can't use the @@identity function because my application uses a
connection pool and it's not garanteed that a connection won't be used
by another request so under a lot of load there could be major problems
and this doens't work:

insert into <table>;
select @@identity;

This doesn't work because the select @@identity might give me the value
of an insert from someone else's request.

Thanks,

Brent

Jul 23 '05 #1
4 41577
On 16 Mar 2005 14:58:25 -0800, br********@gmai l.com wrote:
How do I get the next int value for a column before I do an insert in
MY SQL Server 2000? I'm currently using Oracle sequence and doing
something like:

select seq.nextval from dual;

Then I do my insert into 3 different table all using the same uniqueID.

I can't use the @@identity function because my application uses a
connection pool and it's not garanteed that a connection won't be used
by another request so under a lot of load there could be major problems
and this doens't work:

insert into <table>;
select @@identity;

This doesn't work because the select @@identity might give me the value
of an insert from someone else's request.

Thanks,

Brent


Hi Brent,

Create a stored procedure that starts a transaction, inserts into the
first table, retrieves the identity value used (with SCOPE_IDENTITY, the
recommended method in SQL Server 2000), uses it to insert data into the
other two table, then commits the transaction (or rolls it back if
anything went wrong).

Calling the server three times for three inserts is not only incurring
the overhead of more roundtrips then necessary, you also run the risk of
getting corrupted data: if one insert fails and the others succeed,
you'll have incomplete data in your database. Always include related
modifications in a transaction. And if each call to the database can use
a different connection, then the complete operation, from start to end
of transaction, needs to be done in one call, as transactions are tied
to the connection.

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)
Jul 23 '05 #2
(br********@gma il.com) writes:
insert into <table>;
select @@identity;

This doesn't work because the select @@identity might give me the value
of an insert from someone else's request.


No, @@identity is local to the connection, so it cannot be someone
else's value. Well, if you submit to queries and close your connection
in between, it won't work, but that would be poor practice anyway.

Hugo's suggestion of using a stored procedure is an excellent idea.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #3
On Thu, 17 Mar 2005 22:57:45 +0000 (UTC), Erland Sommarskog
<es****@sommars kog.se> wrote:
(br********@gma il.com) writes:
insert into <table>;
select @@identity;

This doesn't work because the select @@identity might give me the value
of an insert from someone else's request.


No, @@identity is local to the connection, so it cannot be someone
else's value. Well, if you submit to queries and close your connection
in between, it won't work, but that would be poor practice anyway.

Hugo's suggestion of using a stored procedure is an excellent idea.


Excuse me for butting in here, Erland, but there is one 'little'
problem that I have found with @@IDENTITY that I can't see referred to
anywhere, and that anyone relying on it should know about, and that is
that @@IDENTITY can return unexpected values in certain circumstances.

In the supplied example:

insert into <table>
select @@identity

BEAWRE!
If there is a trigger fired during the insert on <table>, and the
trigger performs an insert itself, then @@IDENTITY will return the ID
from the Trigger's insert, not the <table> insert.

This caused me many to lose much more hair than I can afford!

It behaves this way in SQL Server 7, and 2000.

Here is a script to create a test data base:
(Make a new blank database, I called it "Test")

=============== ==============
/****** Object: Table [dbo].[MainTable] Script Date: 18/03/2005
3:10:38 PM ******/
CREATE TABLE [dbo].[MainTable] (
[MainTableId] [int] IDENTITY (1, 1) NOT NULL ,
[LongName] [nvarchar] (255) NOT NULL
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[TriggerTable] Script Date: 18/03/2005
3:10:39 PM ******/
CREATE TABLE [dbo].[TriggerTable] (
[TriggerTableId] [int] IDENTITY (666, 1) NOT NULL ,
[TriggerRowLongN ame] [nvarchar] (255) NOT NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[TriggerTable] WITH NOCHECK ADD
CONSTRAINT [PK_TriggerTable] PRIMARY KEY CLUSTERED
(
[TriggerTableId]
) ON [PRIMARY]
GO
/****** Object: Stored Procedure dbo.Test_sp Script Date:
18/03/2005 3:10:39 PM ******/
CREATE PROCEDURE dbo.Test_sp
AS
INSERT INTO MainTable (LongName) VALUES ('TestLongName' )
SELECT @@IDENTITY
GO
/****** Object: Trigger dbo.MainTable_T rigger1 Script Date:
18/03/2005 3:10:39 PM ******/
CREATE TRIGGER MainTable_Trigg er1
ON dbo.MainTable
FOR INSERT,UPDATE,D ELETE
AS
INSERT INTO TriggerTable (TriggerRowLong Name) VALUES ('Stuff')
GO
=============== ==============

Then, if one executes [Test_sp] in Query Analyser,

EXEC Test_sp

the returned @@IDENTITY is not 1, as you would expect, (this is ID of
the new MainTable row), but 666, which is the ID of the row inserted
via the trigger!
(I seeded this table's identity to begin at 666, in order to show up
clearly)

I would be interested if you were aware of this tiny problemette.
Jul 23 '05 #4
Michael Gray (fl****@newsguy .spam.com) writes:
Excuse me for butting in here, Erland, but there is one 'little'
problem that I have found with @@IDENTITY that I can't see referred to
anywhere, and that anyone relying on it should know about, and that is
that @@IDENTITY can return unexpected values in certain circumstances.

In the supplied example:

insert into <table>
select @@identity

BEAWRE!
If there is a trigger fired during the insert on <table>, and the
trigger performs an insert itself, then @@IDENTITY will return the ID
from the Trigger's insert, not the <table> insert.


Yes, this is a correct observation. For this reason, you should use
scope_identity( ) instead. This function was introduced in SQL 2000.

scope_identity( ) returns the most recently generated IDENTITY in the
current scope, that is a trigger, stored procedure, block of dynamic
SQL etc.

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #5

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

Similar topics

6
34886
by: Jack Tanner | last post by:
I have two complex subqueries that I need to join. I suspect this problem is due to using aliases instead of table names, but I don't know how to work around it (temporary tables?). Please help. SELECT col FROM (subquery-1) AS t1, (subquery-2) AS t2 JOIN t1 ON t2.col = t1.col; >>> Not unique table/alias: 't1'. SELECT col FROM...
2
15082
by: JJA | last post by:
I have fixed length records (167 bytes) in a .txt file and want to load this data exactly as is into a staging table where I hope to be able to later get at selected columns using the SUBSTRING function. Here is my target table: CREATE TABLE JJA_BCP_NHO_DAT ( RecID int IDENTITY(1,1) NOT NULL , Data VARCHAR(167) NOT NULL ) Here is my...
2
9938
by: Bill Holmes | last post by:
I have an A2003 front end (mdb) using ado to link the form/subforms to SQL server 2k tables and views. In SQL server, there is a view between 2 tables with a 1-1 relationship. I can edit records from this view in SQL server. However, in access, I have a form/subform that displays the records but when I try to edit I get the message "Form...
1
495
by: Amos | last post by:
Dear Sirs I am trying to build a cash flow software, first I thought to build one table for each cash and bank account, but talking to some people they suggested me to build one unique table for all bank and cash accounts, putting one more column to identify each bank or cash account. The unique table has this columns structure: ID ...
0
2229
by: nassim.bouayad.agha | last post by:
Unique table version record Hello, I am using a table record to store informations about database dump,I use this table : CREATE TABLE dump_version( count BIGINT unsigned NOT NULL DEFAULT 0, timestamp TIMESTAMP ON UPDATE CURRENT_TIMESTAMP DEFAULT 0 );
0
2070
by: teneesh | last post by:
I created a form in Access to store and retrieve data from a sql server table. When i go and try to add a record to the form - i get the error: Unique Table is nonexistent or not completely specified however if i try to add the same record to the backend database (in sql server), it gets added perfectly. What am i doing wrong? I am using...
3
2918
by: workingbee | last post by:
I’m writing a unittest, which will clear a table and insert a set of values into the table before it starts to test some stored procs. My problem is that when multiple users are running the test at the same time, one user might clear the table after the other user inserts a set of values, which will make the latter user’s test fail. I am...
1
2921
by: shaik mohamed abrar | last post by:
what is the next number in the given sequence 1,2,4,13,31?
0
1670
by: chichbong | last post by:
I have a form in an .adp file in Access 2007, and the project is connected to SQL Server 2005. The form uses a stored procedure to display records. The stored procedure does a JOIN of 2 tables, and has parameters which are passed in through the form's Input Parameters property. It compares the parameters to the corresponding columns and returns...
0
7915
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...
0
7843
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...
0
8205
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7967
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...
0
8220
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6619
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
2347
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
1
1452
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1185
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...

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.