存储过程将使用firstName,lastName,currentPostalCode和newPostalCode作为参数。我只想在有一个人拥有给定的firstName,lastName和currentPostalCode的情况下更新postalCode列。
这是怎么做到的?你使用子查询还是MySQL IF()或其他东西?
感谢。
答案 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
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