Skip to content

Learn online at your pace

DBMS 2: Advanced Databases and Administration

1.1 Stored procedures (notes)

Free preview

Write, call and manage MySQL stored procedures with IN, OUT and INOUT parameters, variables, IF and loops, and handle errors.

What a stored procedure is

A stored procedure is a named block of SQL saved inside the database and run with CALL. Instead of every app (web portal, mobile app, teller system) repeating the same steps to issue a loan, the steps live once in the database.

Benefits: one place for the rules, less network traffic (one call instead of many statements), and security (users can be allowed to run the procedure without direct access to the tables).

Writing a procedure

MySQL statements end with ;, and so do the statements inside a procedure. To tell the client where the whole procedure ends, change the delimiter first.

DELIMITER //
CREATE PROCEDURE add_member(IN p_id CHAR(8), IN p_name VARCHAR(60), IN p_phone VARCHAR(13))
BEGIN
  INSERT INTO members (id_number, full_name, phone, joined_on)
  VALUES (p_id, p_name, p_phone, CURDATE());
END //
DELIMITER ;

CALL add_member('34567812', 'Wanjiru Kamau', '0722111222');

Parameters and variables

  • IN: a value passed into the procedure (the default).
  • OUT: a value the procedure sends back.
  • INOUT: passed in, changed and sent back.
DELIMITER //
CREATE PROCEDURE member_savings(IN p_member INT, OUT p_total DECIMAL(12,2))
BEGIN
  SELECT IFNULL(SUM(amount), 0) INTO p_total FROM savings WHERE member_id = p_member;
END //
DELIMITER ;

CALL member_savings(101, @total);
SELECT @total;

Local variables are declared at the top with DECLARE v_limit DECIMAL(12,2) DEFAULT 0;. Variables starting with @ are session variables that live until you disconnect.

Decisions and loops

DELIMITER //
CREATE PROCEDURE issue_loan(IN p_member INT, IN p_amount DECIMAL(12,2))
BEGIN
  DECLARE v_saved DECIMAL(12,2);
  SELECT IFNULL(SUM(amount), 0) INTO v_saved FROM savings WHERE member_id = p_member;
  IF p_amount > v_saved * 3 THEN
    SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Loan exceeds 3 times savings';
  ELSE
    INSERT INTO loans (member_id, amount, issued_on, status)
    VALUES (p_member, p_amount, CURDATE(), 'active');
  END IF;
END //
DELIMITER ;

SIGNAL raises a custom error that the calling app receives. MySQL also has WHILE ... DO ... END WHILE, REPEAT ... UNTIL ... END REPEAT and LOOP with LEAVE.

Handling errors

A handler decides what happens when an error occurs inside the procedure:

DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
  ROLLBACK;
  RESIGNAL;   -- pass the error on to the caller
END;

Managing procedures

SHOW PROCEDURE STATUS WHERE Db = 'tumaini_sacco';
SHOW CREATE PROCEDURE issue_loan;
DROP PROCEDURE IF EXISTS issue_loan;
GRANT EXECUTE ON PROCEDURE tumaini_sacco.issue_loan TO 'teller'@'%';

Key words

  • Stored procedure, CALL, DELIMITER.
  • IN, OUT, INOUT parameters; DECLARE local variables; @session variables.
  • IF, WHILE, REPEAT, LOOP.
  • SIGNAL (raise an error), handler (catch an error).

Try it yourself

  1. Write a procedure record_saving(member, amount, code) that rejects amounts below 100.
  2. Write a procedure with an OUT parameter returning a member's number of active loans.
  3. Grant a teller EXECUTE on your procedure but no INSERT on the tables.