Solved

returning primary key after update

Posted on 2013-01-04
2
392 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

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

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

Suggested Solutions

Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

776 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