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 f开发者_StackOverflow社区or the ID, how can I get this?
The @@identity
and scope_identity()
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 it is a different field, you should 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
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
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
精彩评论