[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

returning primary key after update

Posted on 2013-01-04
2
Medium Priority
?
415 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 23

Accepted Solution

by:
Steve Wales earned 2000 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

This month, Experts Exchange sat down with resident SQL expert, Jim Horn, for an in-depth look into the makings of a successful career in SQL.
This shares a stored procedure to retrieve permissions for a given user on the current database or across all databases on a server.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.
Suggested Courses

872 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