2

我在 SQL Server 中有一个表,它有一个 PK ( ID) 和另一个由其他几列组成的(逻辑)主键(尽管没有 UNIQUE 约束)。比方说,表PERSON,,PK = PERSON_ID然后NAME,,SURNAMEAGE

我想可以说

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

并且仅在“更新的行”= 1 时才执行,否则(超过 1 行)根本不执行。问题是我不确定 NAME 和 SURNAME 是否唯一标识一条记录,并且我无法先验地告诉它。

想法?

4

5 回答 5

7

试试下面的查询......它会帮助你

UPDATE PERSON 
SET AGE = 43 
WHERE NAME = 'XX' 
  AND SURNAME = 'YYY' 
  AND 1 = (SELECT COUNT(*) FROM PERSON WHERE NAME = 'XX' AND SURNAME = 'YYY)
于 2013-02-01T16:11:53.523 回答
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'
于 2013-02-01T16:51:36.837 回答
3

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

BEGIN TRAN
UPDATE PERSON SET AGE = 43 WHERE NAME = 'XX' AND SURNAME = 'YYY'
IF @@ROWCOUNT > 1 ROLLBACK TRAN ELSE COMMIT TRAN
于 2017-05-04T06:52:51.357 回答
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)
于 2013-02-01T19:53:57.723 回答
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)
于 2013-02-01T16:05:44.050 回答