7

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). Let's say, table PERSON, PK = PERSON_ID, then NAME, SURNAME, AGE

I'd like it was possible to say

UPDATE PERSON SET AGE = 43 WHERE NAME = 'XX' AND SURNAME = 'YYY'

and have it executed only if 'updated rows' = 1, otherwise (more than 1 row) NO EXECUTION at all. The problem is that I'm not sure if NAME and SURNAME uniquely identify a record, and I have no way to tell it a priori.

Ideas?

Pondlife
  • 15,992
  • 6
  • 37
  • 51
Diego Pascotto
  • 329
  • 2
  • 13
  • possible duplicate of [SQL update top1 row query](http://stackoverflow.com/questions/3860975/sql-update-top1-row-query) and [Update a single row with t-sql](http://stackoverflow.com/questions/2909118/update-a-single-row-with-t-sql) and [SQL query to update top 1 record in table](http://stackoverflow.com/questions/3855528/sql-query-to-update-top-1-record-in-table) – Kermit Feb 01 '13 at 16:03
  • @njk -- not a duplicate; in this case, the user only wants to execute if one row would be updated, and not simply to update the first record. – LittleBobbyTables - Au Revoir Feb 01 '13 at 16:04
  • @LittleBobbyTables My apologies. – Kermit Feb 01 '13 at 16:07

5 Answers5

8

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)
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Pandian
  • 8,848
  • 2
  • 23
  • 33
6

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
duckbenny
  • 604
  • 7
  • 7
5

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'
Ben
  • 309
  • 1
  • 3
1

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)
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
1
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)
paparazzo
  • 44,497
  • 23
  • 105
  • 176