Getting the Id of a row I updated in Sql Server

Viewed 71222

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 Answers

I think what @pauloya tried to say is:

if you will update a table then you have a WHERE clause, so if you use that same where clause on a select with an INTO #tempTable you have all rows affected by your UPDATE.

So you can go:

SELECT
    userName.ID
INTO #temp
FROM ITS2_UserNames AS userNames
WHERE @Customer_ID = TCID AND @Handle_ID = ID

then you update

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

finally you can return all IDs affected by your update

SELECT * FROM #temp

You can do this with OUTPUT but you will have to declare a variable table like

DECLARE @tempTable TABLE ( ID INT );

and then you use OUTPUT

UPDATE ITS2_UserNames  
SET AupIp = @AupIp  
OUTPUT INSERTED.ID
INTO @tempTable
WHERE @Customer_ID = TCID AND @Handle_ID = ID

Wanted to mention here that if you want to take affected row's primary key in variable then you can use OUTPUT clause which can put this in a table variable. Execute below statements for example...

CREATE TABLE ItemTable(ID INT IDENTITY(1,1),Model varchar(500) NULL, Color VARCHAR(50) null)

INSERT INTO ItemTable(Model, Color) VALUES('SomeModel', 'Yellow')

INSERT INTO ItemTable(Model, Color) VALUES('SomeModel', 'Red')

INSERT INTO ItemTable(Model, Color) VALUES('SomeModel', 'Pink')

DECLARE @LastUpdateID TABLE(ItemID INT null)

UPDATE ItemTable SET model = 'abc' OUTPUT INSERTED.ID INTO @LastUpdateID WHERE Color = 'Red'

SELECT ItemID FROM @LastUpdateID

enter image description here

Related