Solved

returning primary key after update

Posted on 2013-01-04
2
389 Views
Last Modified: 2013-01-04
I use this appended to an INSERT statement (using Dim PK as long = Command.ExecuteScalar() ) to return the primary key:

SELECT @@Identity

How do I do the same for an UPDATE?  I am geting a NULL back.
0
Comment
Question by:HLRosenberger
2 Comments
 
LVL 22

Accepted Solution

by:
Steve Wales earned 500 total points
ID: 38745503
First off, read this about @@IDENTITY:

http://msdn.microsoft.com/en-us/library/ms187342.aspx

That value is populated as the value of the last identity value generated by a statement.

An update statement shouldn't be automatically generating new identity values (unless you're somehow playing with the value of the identity column?)

In an update statement you're dealing with an existing row, not a newly generated one.

Select the value of the identity column you're updating from the table after the update - the value will be there, it's not something that's newly generated.

If I have a new table with an identity column and I insert 5 rows, @@IDENTITY should return 5 (assuming I start with 1 and increment by 1).

If I come back later and try to update row #5, I need to know the value of the row I'm updating to somehow identify it.  I can select from the table after the update where there is some means of identifying the row (a customer number or PO number or whatnot) and check the value of the identity column as a part of that query.
0
 
LVL 1

Author Closing Comment

by:HLRosenberger
ID: 38745518
I understand  Thanks!
0

Featured Post

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Via a live example, show how to shrink a transaction log file down to a reasonable size.

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now