tags:

views:

109

answers:

3

I'm trying to return the Id of a row I update in sql

UPDATE ITS2_UserNames
  SET AupIp = @AupIp
  WHERE @Customer_ID = TCID AND @Handle_ID = ID

  SELECT @@ERROR AS Error, @@ROWCOUNT AS RowsAffected, SCOPE_IDENTITY() AS ID

and I keep getting Null for the ID, how can I get this?

+4  A: 

The @@identity and scope_identy() will hand you the identity of a new row, ie. after an insert. After your update, the identity of the row is... @Customer_ID or @Handle_Id? If is a different field, you shoudl use the OUTPUT clause to return the ID of the updated row:

UPDATE ITS2_UserNames  
SET AupIp = @AupIp  
OUTPUT INSERTED.PrimaryKeyID
WHERE @Customer_ID = TCID AND @Handle_ID = ID
Remus Rusanu
Assuming he's on SQL2005/2008, of course
CodeByMoonlight
No, it's in SQL 2000 as well
CodeByMoonlight
@CodeByMoonlight: You're right
Remus Rusanu
I can't find any evidence that this worked on SQL Server 2000... not from my memory, not from any blog posts, and not from official documentation. In fact there are several places in SQL Server 2005 Books Online where they tout "the new OUTPUT clause." When I try the above in 2000, I get a syntax error, as I would expect. What leads you to believe this works in SQL Server 2000? May be a moot point anyway. Wish there was a way to force questions to include version information.
Aaron Bertrand
@Aaron: Code was talking about the use of SCOPE_IDENTITY(), sry for confusion, I deleted one of my own comments and this disrupted the meaning.
Remus Rusanu
Gotcha, I spent half an hour trying to figure out why everyone suddenly thought OUTPUT was supported in 2000. I was only 99.99999% sure it wasn't. :-)
Aaron Bertrand
A: 

If you want to find out the records that match that update you should do a select with it

Select IdColumn
From ITS2_UserNames
WHERE @Customer_ID = TCID AND @Handle_ID = ID
Paulo Manuel Santos
+1  A: 

Aren't you identifying the IDENTITY value of the row already with @Handle_ID? If so, then just use:

  SELECT @@ERROR AS Error, @@ROWCOUNT AS RowsAffected, @Handle_ID AS ID;

If not, then can you explain which column is the IDENTITY column?

Aaron Bertrand