2

存储过程将接受 firstName、lastName、currentPostalCode 和 newPostalCode 作为参数。只有当有一个人具有给定的 firstName、lastName 和 currentPostalCode 时,我才想更新 postalCode 列。

这是怎么做到的?您是否使用子查询或 MySQL IF() 或其他东西?

谢谢。

4

1 回答 1

3

您不需要任何花哨的条件逻辑来执行此操作,只需UPDATE带有WHERE子句的常规语句即可。WHERE如果子句没有匹配任何行,则不会发生更新。

/* Update the records with matching name & postcode */
UPDATE  yourtable
  SET postalCode = 'newPostalCode'
WHERE
  /* If all 3 conditions don't match, nothing gets updated */
  firstName = 'firstName'
  AND lastName = 'lastName'
  AND postalCode = 'oldPostalCode'

作为存储过程:

CREATE PROCEDURE updatePostalCode (
  IN in_firstName VARCHAR(64),
  IN in_lastName VARCHAR(64),
  IN in_oldPostalCode VARCHAR(16),
  IN in_newPostalCode VARCHAR(16)
)
BEGIN
  UPDATE yourtable 
  SET
    postalCode = in_newPostalCode 
  WHERE 
    lastName = in_lastName 
    AND firstName = in_firstName 
    AND postalCode = in_oldPostalCode;
END

附录:如果你真的只想在只有一个匹配的情况下这样做......

要仅在恰好有一个匹配行(不是 2 个或更多)的情况下更新,您仍然可以使用普通的更新语句,在WHERE子句中添加一个额外的子查询

UPDATE  yourtable
  SET postalCode = 'newPostalCode'
WHERE
  /* If all 3 conditions don't match, nothing gets updated */
  firstName = 'firstName'
  AND lastName = 'lastName'
  AND postalCode = 'oldPostalCode'
  /* Result of count subquery = 1 */
  AND (
    SELECT COUNT(*) AS matched 
    FROM yourtable 
    WHERE firstName = 'firstName' AND lastName = 'lastName' AND postalCode = 'oldPostalCode'
  ) = 1

附录 2 如果不完全匹配则错误退出:

CREATE PROCEDURE updatePostalCode (
  IN in_firstName VARCHAR(64),
  IN in_lastName VARCHAR(64),
  IN in_oldPostalCode VARCHAR(16),
  IN in_newPostalCode VARCHAR(16)
)
BEGIN
  DECLARE num_matched INT;
  SET num_matched = (SELECT COUNT(*) FROM yourtable WHERE firstName = 'firstName' AND lastName = 'lastName' AND postalCode = 'oldPostalCode');

  IF (num_matched <> 1) THEN 
     /* Trigger an error and exit */
     LEAVE updatePostalCode
  END IF

  /* Perform the UPDATE statement */
END
于 2012-11-22T20:30:23.127 回答