Getting the Id of a row I updated in Sql Server

前端 未结 4 736
别那么骄傲
别那么骄傲 2020-12-01 10:27

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 @         


        
相关标签:
4条回答
  • 2020-12-01 11:03

    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
    
    0 讨论(0)
  • 2020-12-01 11:07

    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  
    
    0 讨论(0)
  • 2020-12-01 11:23

    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

    0 讨论(0)
  • 2020-12-01 11:28

    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
    
    0 讨论(0)
提交回复
热议问题