stored procedures in Mysql tutorial
Following is one of the sample of stored procedure created in mysql
whenever we create any store procuedure we need to make sure store procedure with same name must not be present in the database already.
DROP PROCEDURE `InsertingContactDetails`//
Following is the sample code to create stored procedure in default xampp database.
Create definer will define our store procedure variables as shown below which we can use
in our different blocks of stored procedure.
CREATE DEFINER=`root`@`localhost` PROCEDURE `InsertingContactDetails`(
p_nick_name VARCHAR(50),
p_first_name VARCHAR(50),
p_last_name VARCHAR(50),
p_email_address VARCHAR(100),
OUT p_status INT(1),
OUT p_message VARCHAR(200)
)
To start any stored procedure block we have to use BEGIN statement.
There could be nested stored procedure blocks embeded within each other. These blocks are similar
to any programming language code like cpp, c , perl or shell script etc.
BEGIN
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
SELECT 0 INTO p_status;
SELECT 'Error in Adding' INTO p_message;
// Nested block of code
BEGIN
// Conditional statement
IF (p_type = 'MGR') THEN
INSERT INTO manager_details
(contact_nick_name, contact_first_name, contact_last_name, contact_email_address)
VALUES
(p_nick_name, p_first_name, p_last_name, p_email_address);
SET @v_ins_row_count := ROW_COUNT();
IF ( @v_ins_row_count > 0) THEN
SET p_status = 1;
SET p_message = 'Added Successfully';
ELSE
SET p_status = 0;
SET p_message = 'Error in Adding';
END IF ;
ELSEIF (p_type = 'WTR') THEN
INSERT INTO waiter_details
(contact_nick_name, contact_first_name, contact_last_name, contact_email_address)
VALUES
(p_nick_name, p_first_name, p_last_name, p_email_address);
SET @v_ins_row_count := ROW_COUNT();
IF ( @v_ins_row_count > 0) THEN
SET p_status = 1;
SET p_message = 'Added Successfully';
ELSE
SET p_status = 0;
SET p_message = 'Error in Adding';
END IF ; // End of conditional statement.
ELSE
SET p_status = 0;
SET p_message = 'Error in Adding';
END IF;
END ;