473,623 Members | 2,453 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Getting list of recently added IDENTITY items

In a multi-user environment, I would like to get a list of Ids
generated, similar to:

declare @LastId int
select @LastId = Max(Id) From TableMania

INSERT INTO TableMania (ColumnA, ColumnB)
SELECT ColumnA, ColumnB From OtherTable Where ColumnC > 15

--get entries just added
SELECT * FROM TableMania WHERE Id > @LastId
The above works fine, except I'm assuming it will not work in a
multi-user environment. Is there any way to get the set of Ids that
were just added in the previous statement (similar to @@IDENTITY)
without doing all of this in a serializable transaction or making a
temp table of every single Id before the insert statement?

Mar 8 '06 #1
41 3143
pb648174 (go****@webpaul .net) writes:
In a multi-user environment, I would like to get a list of Ids
generated, similar to:

declare @LastId int
select @LastId = Max(Id) From TableMania

INSERT INTO TableMania (ColumnA, ColumnB)
SELECT ColumnA, ColumnB From OtherTable Where ColumnC > 15

--get entries just added
SELECT * FROM TableMania WHERE Id > @LastId
The above works fine, except I'm assuming it will not work in a
multi-user environment. Is there any way to get the set of Ids that
were just added in the previous statement (similar to @@IDENTITY)
without doing all of this in a serializable transaction or making a
temp table of every single Id before the insert statement?


Actually, I don't know.

Say that you insert a couple of rows into a table with a column ident
that has the IDENTITY property. @@identity or scope_identity gives
you the highest value for ident for the lnserted rows. But is the
lowest value @@identity - @@rowcount + 1?

I have never seen any documentation that guarantees this to be true.
It is likely to be, but what if you insert 10000 rows, and in the
middle of this another users needs to insert a single row. Will he
steal a value?

One strategy would be to retrieve ident_current() before the insertion (or
MAX(ident), and then after the insertion check that the interval is equal
to @@rowcount, and bail out if it's not.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Mar 8 '06 #2
sure.
get a timestamp, including milliseconds from the local workstation.
insert that timestamp into a column.
then you can group by timestamp.

Mar 9 '06 #3
I guess I will just go with a serializable transaction for now...

Mar 11 '06 #4
pb648174 wrote:
In a multi-user environment, I would like to get a list of Ids
generated, similar to:

declare @LastId int
select @LastId = Max(Id) From TableMania

INSERT INTO TableMania (ColumnA, ColumnB)
SELECT ColumnA, ColumnB From OtherTable Where ColumnC > 15

--get entries just added
SELECT * FROM TableMania WHERE Id > @LastId
The above works fine, except I'm assuming it will not work in a
multi-user environment. Is there any way to get the set of Ids that
were just added in the previous statement (similar to @@IDENTITY)
without doing all of this in a serializable transaction or making a
temp table of every single Id before the insert statement?


This is easy to solve provided you have an alternate key. IDENTITY
should not be the only key of a table and this is one example of why -
without an alternate key you have no entity integrity so you cannot
always guarantee reliable results from the data.

Try the following example. Notice that the reason this works is that
the INSERT list always must include the primary key when you are
inserting multiple rows (otherwise there is no key). The only potential
exception is where you assign a default value that forms part of the
key - for example DEFAULT CURRENT_TIMESTA MP. In that case you need to
retrieve the default value before you do the INSERT so that you can use
it in the SELECT.

CREATE TABLE tablemania (id INT IDENTITY PRIMARY KEY, a INT, b INT,
UNIQUE (a,b));
CREATE TABLE othertable (a INT, b INT, c INT, PRIMARY KEY (a,b,c));

INSERT INTO othertable (a,b,c)
SELECT 1,2,16 UNION ALL
SELECT 1,3,16 UNION ALL
SELECT 1,4,16 UNION ALL
SELECT 1,5,16 ;

DECLARE @t TABLE (a INT, b INT, PRIMARY KEY (a,b));

INSERT INTO @t (a, b)
SELECT a, b
FROM othertable
WHERE c > 15 ;

INSERT INTO tablemania (a, b)
SELECT a, b
FROM @t ;

SELECT T.id, T.a, T.b
FROM tablemania AS T
JOIN @t AS O
ON T.a = O.a
AND T.b = O.b ;

In SQL Server 2005 you have a more concise alternative. Use the OUTPUT
option:

INSERT INTO tablemania (a, b)
OUTPUT inserted.id, inserted.a, inserted.b
SELECT a, b
FROM othertable
WHERE c > 15 ;

Hope this helps.

--
David Portas, SQL Server MVP

Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.

SQL Server Books Online:
http://msdn2.microsoft.com/library/m...S,SQL.90).aspx
--

Mar 11 '06 #5
Erland Sommarskog wrote:
pb648174 (go****@webpaul .net) writes:
In a multi-user environment, I would like to get a list of Ids
generated, similar to:

declare @LastId int
select @LastId = Max(Id) From TableMania

INSERT INTO TableMania (ColumnA, ColumnB)
SELECT ColumnA, ColumnB From OtherTable Where ColumnC > 15

--get entries just added
SELECT * FROM TableMania WHERE Id > @LastId
The above works fine, except I'm assuming it will not work in a
multi-user environment. Is there any way to get the set of Ids that
were just added in the previous statement (similar to @@IDENTITY)
without doing all of this in a serializable transaction or making a
temp table of every single Id before the insert statement?
Actually, I don't know.

Say that you insert a couple of rows into a table with a column ident
that has the IDENTITY property. @@identity or scope_identity gives
you the highest value for ident for the lnserted rows. But is the
lowest value @@identity - @@rowcount + 1?

I have never seen any documentation that guarantees this to be true.
It is likely to be, but what if you insert 10000 rows, and in the
middle of this another users needs to insert a single row. Will he
steal a value?


Tibor posted a repro that demonstrates the values are not always
contiguous. Also there is a related problem with IGNORE_DUP_KEY, which
causes gaps if rows are ignored.
http://groups.google.co.uk/group/mic...5cbb8f978decc9

One strategy would be to retrieve ident_current() before the insertion (or
MAX(ident), and then after the insertion check that the interval is equal
to @@rowcount, and bail out if it's not.


See my solutions in this thread.

--
David Portas, SQL Server MVP

Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.

SQL Server Books Online:
http://msdn2.microsoft.com/library/m...S,SQL.90).aspx
--

Mar 11 '06 #6
David Portas (RE************ *************** *@acm.org) writes:
Tibor posted a repro that demonstrates the values are not always
contiguous. Also there is a related problem with IGNORE_DUP_KEY, which
causes gaps if rows are ignored.
http://groups.google.co.uk/group/mic...ogramming/msg/
375cbb8f978decc 9

Ah, that was interesting!
This is easy to solve provided you have an alternate key. IDENTITY
should not be the only key of a table and this is one example of why -
without an alternate key you have no entity integrity so you cannot
always guarantee reliable results from the data.
That is about as useful as saying "this is a good car, but you should
not drive it at night". If databases would only include data that
have natural keys, there wouldn't be much data in them.

What I didn't say in my first post, is that my take on this is usually
to not have IDENTITY on my surrogate key, but instead bounce data over
a temp table with IDENTITY, and then add that to a SELECT MAX(id)
from the target table. This comes with scaling problems obviously, but
that has not been an issue for me, luckily.
In SQL Server 2005 you have a more concise alternative. Use the OUTPUT
option:

INSERT INTO tablemania (a, b)
OUTPUT inserted.id, inserted.a, inserted.b
SELECT a, b
FROM othertable
WHERE c > 15 ;


I will have to admit that I not really seen the point with the OUTPUT
clause for INSERT, but this an excellent use for it!

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

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Mar 11 '06 #7
Erland Sommarskog wrote:
That is about as useful as saying "this is a good car, but you should
not drive it at night". If databases would only include data that
have natural keys, there wouldn't be much data in them.


You said "data" so you could be right. If you'd said "informatio n"
you'd be wrong. Here's an analogy. If I have two copies of "Inside SQL
Server" on my bookshelf do I have more information than if I have one
copy of that book? Now if I write 1 on the cover of the first book and
2 on the cover of the second, do I have any more information? So should
I spend money and storage space on two books or one? The smart money is
invested in information not in data.

--
David Portas, SQL Server MVP

Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.

SQL Server Books Online:
http://msdn2.microsoft.com/library/m...S,SQL.90).aspx
--

Mar 11 '06 #8
David Portas (RE************ *************** *@acm.org) writes:
You said "data" so you could be right. If you'd said "informatio n"
you'd be wrong. Here's an analogy. If I have two copies of "Inside SQL
Server" on my bookshelf do I have more information than if I have one
copy of that book? Now if I write 1 on the cover of the first book and
2 on the cover of the second, do I have any more information? So should
I spend money and storage space on two books or one? The smart money is
invested in information not in data.


Then again, you could have scribbled notes in one of the copies, and
the other could have Kalen's highly valuable autograph.

More importantly, there is data - or information - out there that
users want to - and need to - deal with, despite that we cannot define
a unique key for them. You already know the prime example too well:
customers.

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

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Mar 11 '06 #9
Erland Sommarskog wrote:
David Portas (RE************ *************** *@acm.org) writes:
You said "data" so you could be right. If you'd said "informatio n"
you'd be wrong. Here's an analogy. If I have two copies of "Inside SQL
Server" on my bookshelf do I have more information than if I have one
copy of that book? Now if I write 1 on the cover of the first book and
2 on the cover of the second, do I have any more information? So should
I spend money and storage space on two books or one? The smart money is
invested in information not in data.
Then again, you could have scribbled notes in one of the copies, and
the other could have Kalen's highly valuable autograph.


In that case they wouldn't be duplicates any more. To complete the
analogy, you now have a natural key. (Alternatively you might want to
decompose the notes and the signature into separate tables)
More importantly, there is data - or information - out there that
users want to - and need to - deal with, despite that we cannot define
a unique key for them. You already know the prime example too well:
customers.


Users are concerned with information. Data (how the information is
represented) is primarily the concern of database professionals. As a
database designer you have a choice because the same information can
always be modelled with natural keys or without. You can argue that the
developer may lack the time, the resources or the authority to redesign
his database. He may even be unable to analyse his business problem
well enough to identify a suitable key with a high degree of
confidence. However, those constraints are not problems we can solve in
a newsgroup. They are project management problems rather than technical
ones.

The technical solution to the OP's problem is simple: elminate
redundancy. It is always possible to eliminate redundancy as a
consequence of the simple fact that duplicate rows cannot contain more
information than a single row. That applies equally whether the row
represents customers or books or anything else. I suggest we let the OP
to decide if he has the will or the resources to implement the solution
in his case.

--
David Portas, SQL Server MVP

Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.

SQL Server Books Online:
http://msdn2.microsoft.com/library/m...S,SQL.90).aspx
--

Mar 12 '06 #10

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

Similar topics

2
3816
by: Andrea | last post by:
Hi, I'm trying to emulate part of our client-server application as a web site so customers can use it, and I'm stuck when it comes to re-ordering items in a list. Basically we have a list of available articles ("availableItems") and a list of articles already in an issue ("selectedItems"). What I want is to be able to move articles freely between the two lists and then on submission add them to the issue (which I can), but also move...
15
2955
by: sara | last post by:
Hi I'm pretty new to Access here (using Access 2000), and appreciate the help and instruction. I gave myself 2.5 hours to research online and help and try to get this one, and I am not getting it. Simple database: I want to have a user enter Supply Orders (just for tracking purposes) by Item. The user may also enter a new item - "new" is a combination of Item, PartNumber and Vendor - they could have the
84
3885
by: Bibby | last post by:
Hi, I'm interested in getting started in the programming world. I've dabbled in C, C++ and VB6. Which would be the best language to focus my attention to regarding the following considerations: Hireability Portability Flexibility The likely candidates seem to be Java, VB.Net, C, C++, C#.
2
2529
by: Wayne Wengert | last post by:
I have a VB.NET app in which I am using the following code to add a new row. ds.Tables("UnitsTable").Rows.Add(dr) ' Add the new row da.InsertCommand = cmdBuilder.GetInsertCommand da.Update(ds, "UnitsTable") At this point I want to get the value of the Identity field that has just been added to the underlying table ("UnitsTable" is based on a Select against a table named "Units")
43
2706
by: michael.f.ellis | last post by:
The following script puzzles me. It creates two nested lists that compare identically. After identical element assignments, the lists are different. In one case, a single element is replaced. In the other, an entire column is replaced. --------------------------------------------------------------------------------------- ''' An oddity in the behavior of lists of lists. Occurs under Python 2.4.3 (#69, Mar 29 2006, 17:35:34)
6
2735
by: AA Arens | last post by:
Hi, I have a database with 2 main forms. Contacts and companies. I share the base with two others via LAN. On the companies form I have buttons to navigate throught the records (>400). We are mostly handling let say 5 companies. Every time I have to navigate or choose the find record button to get the right company. I am looking fo a feature to have listed in a combo list the last 5 visited records ("recently visited records").
7
19470
by: Ivan Voras | last post by:
For a declaration like: List<MyTypeitems = ... where MyType is a struct, attempt to modify an item with items.member = something; fails with the message:
0
8227
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
8165
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,...
0
8670
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8613
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8326
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,...
0
8469
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5561
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
4164
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1473
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.