mysql procedure code example

Example 1: mysql create stored procedure

-- MySQL

-- example
DELIMITER $$ -- Changes delimiter to $$ so can use ; within the procedure
CREATE PROCEDURE select_employees()
BEGIN
	select * 
	from employees 
	limit 1000; -- Use the ; symbol within the procedure
END$$ 
DELIMITER ; -- Resets the delimiter

/* syntax:
DELIMITER $$ -- Changes delimiter to $$ so can use ; within the procedure
CREATE PROCEDURE <Your-procedure-name>(<argument1><argument2>...<argumentN>)
BEGIN
	<Code-that-stored-procedure-executes>; -- Use the ; symbol within the procedure
END$$
DELIMITER ; -- Resets the delimiter
*/

Example 2: mysql create function

-- MySQL

-- example
DELIMITER $$
CREATE FUNCTION f_employee_count(p_dept_no INTEGER) RETURNS INTEGER
  DETERMINISTIC NO SQL READS SQL DATA
  BEGIN
    DECLARE v_emp_count INTEGER;

    SELECT COUNT(*)
    INTO v_emp_count
    FROM EMPLOYEES E
    WHERE E.DEPT_NO = p_dept_no
    GROUP BY DEPARTMENT_NO;

    RETURN v_emp_count;
END$$
DELIMITER ;

/* syntax:
DELIMITER $$
CREATE FUNCTION <Your-procedure-name>(<arguments>) RETURNS <date-type>
  DETERMINISTIC NO SQL READS SQL DATA
  BEGIN
      DECLARE <variable-name> <data-type>

      <Code-that-sets-the-output-variable>; 

      RETURN <variable-name>;
END$$
DELIMITER ;
*/

Example 3: mysql stored procedure

Syntax:
-------------------
CREATE [DEFINER = { user | CURRENT_USER }]          
PROCEDURE sp_name ([proc_parameter[,...]])          
[characteristic ...] routine_body    
proc_parameter: [ IN | OUT | INOUT ] param_name type    
type:          
Any valid MySQL data type    
characteristic:          
COMMENT 'string'     
| LANGUAGE SQL      
| [NOT] DETERMINISTIC      
| { CONTAINS SQL | NO SQL | READS SQL DATA 
| MODIFIES SQL DATA }      
| SQL SECURITY { DEFINER | INVOKER }    
routine_body:      
Valid SQL routine statement

Example
mysql> DELIMITER $$ ;
mysql> CREATE PROCEDURE student_details()
> SELECT * FROM student_details; $$
Query OK, 0 rows affected (0.00 sec)

Tags:

Sql Example