如果一行受到影响,如何执行UPDATE?

时间:2013-02-01 16:00:28

标签: sql-server tsql

我在SQL Server中有一个表,其中有一个PK(ID)和另一个(逻辑)主键由其他几列创建(尽管没有UNIQUE约束)。我们先说PERSONPK = PERSON_ID,然后NAMESURNAMEAGE

我希望可以说

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

并且只有在更新的行' = 1,否则(超过1行)根本不执行。问题是我不确定NAME和SURNAME是否唯一地标识了一条记录,我无法先验地说出来。

想法?

5 个答案:

答案 0 :(得分:5)

尝试以下查询...它会帮助您

UPDATE PERSON 
SET AGE = 43 
WHERE NAME = 'XX' 
  AND SURNAME = 'YYY' 
  AND 1 = (SELECT COUNT(*) FROM PERSON WHERE NAME = 'XX' AND SURNAME = 'YYY)

答案 1 :(得分:3)

我在更新之前而不是在where子句中放置条件。

IF (SELECT COUNT(*) FROM PERSON WHERE NAME = 'XX' AND SURNAME = 'YYY') = 1
UPDATE PERSON SET AGE = 43 WHERE NAME = 'XX' AND SURNAME = 'YYY'

答案 2 :(得分:2)

我不是编写复杂的WHERE子句或IF语句,而是将整个事物包装在事务中并检查@@ ROWCOUNT:

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

答案 3 :(得分: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
  GROUP BY p2.NAME, p2.SURNAME
  HAVING COUNT(*) > 1)

答案 4 :(得分: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)