David
David

Reputation: 210

MySQL Stored Procedure and only update if certain condition

The stored procedure is goin to take in a firstName, lastName, currentPostalCode and newPostalCode as arguements. I want to update the postalCode column only if there is one person with the given firstName, lastName and currentPostalCode.

How is this done? Do you use sub queries or the MySQL IF() or something else?

Thanks.

Upvotes: 2

Views: 3727

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270607

You don't need any fancy conditional logic to perform this action, just a regular UPDATE statement with a WHERE clause will do it. If no rows is matched by the WHERE clause, no update takes place.

/* 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'

As a stored procedure:

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

Addendum: If you really only want to do this if there is exactly one match...

To update only in the event of exactly one matching row (not 2 or more), you can still use a plain update statement, with an additional subquery in the WHERE clause

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

Addendum 2 To exit with error if there is not exactly one match:

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

Upvotes: 3

Related Questions