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

后端 未结 5 934
隐瞒了意图╮
隐瞒了意图╮ 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:12

    something like that should do it.

    UPDATE Person p1
    SET p1.AGE = 43
    WHERE NAME = 'XX' AND SURNAME = 'YY'
    AND NOT EXISTS (
      SELECT NULL FROM Person p2
      WHERE p1.NAME = p2.NAME
      AND p1.SURNAME = p2.SURNAME
      GROUP BY p2.NAME, p2.SURNAME
      HAVING COUNT(*) > 1)
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-21 13:24
    UPDATE Person p1
    SET p1.AGE = 43
    WHERE NAME = 'XX' AND SURNAME = 'YY'
    AND NOT EXISTS (
      SELECT NULL FROM Person p2
      WHERE p1.NAME = p2.NAME
      AND p1.SURNAME = p2.SURNAME
      AND p1.ID <> p2.ID)
    
    0 讨论(0)
  • 2021-01-21 13:26

    I'd put the conditional before the update rather than in the where clause.

    IF (SELECT COUNT(*) FROM PERSON WHERE NAME = 'XX' AND SURNAME = 'YYY') = 1
    UPDATE PERSON SET AGE = 43 WHERE NAME = 'XX' AND SURNAME = 'YYY'
    
    0 讨论(0)
  • 2021-01-21 13:30

    Try the below query... it will help you

    UPDATE PERSON 
    SET AGE = 43 
    WHERE NAME = 'XX' 
      AND SURNAME = 'YYY' 
      AND 1 = (SELECT COUNT(*) FROM PERSON WHERE NAME = 'XX' AND SURNAME = 'YYY)
    
    0 讨论(0)
提交回复
热议问题