How to execute an UPDATE only if one row would be affected?

后端 未结 5 1034
隐瞒了意图╮
隐瞒了意图╮ 2021-01-21 12:44

I have a table in SQL Server that has a PK (ID) and another (logical) primary key made by a couple of other columns (although there is no UNIQUE constraint on that)

5条回答
  •  难免孤独
    2021-01-21 13:15

    Rather than writing a complex WHERE clause or IF statement, I usually just wrap the whole thing in a transaction and check @@ROWCOUNT:

    BEGIN TRAN
    UPDATE PERSON SET AGE = 43 WHERE NAME = 'XX' AND SURNAME = 'YYY'
    IF @@ROWCOUNT > 1 ROLLBACK TRAN ELSE COMMIT TRAN
    

提交回复
热议问题