MySQL存储过程并且仅在某些条件下更新

时间:2012-11-22 20:16:55

标签: mysql sql stored-procedures

存储过程将使用firstName,lastName,currentPostalCode和newPostalCode作为参数。我只想在有一个人拥有给定的firstName,lastName和currentPostalCode的情况下更新postalCode列。

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

感谢。

1 个答案:

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