Engineering Full Stack Apps with Java and JavaScript
Here we discuss examples for different cases of usage for stored procedures and stored functions. Please refer to the note on ‘Stored Procedures and Stored Functions in MySQL’ for more theory, details and explanations.
Example cases discussed here are:
DROP TABLE IF EXISTS emp;
CREATE TABLE emp(`first name` VARCHAR(20), id INT PRIMARY KEY);
insert into emp values('HJK', 1);
insert into emp values('ABC', 2);
insert into emp values('DEF', 3);
Verify Using:
select * from emp;
DELIMITER |
CREATE PROCEDURE sample_sp_no_param ()
BEGIN
UPDATE emp SET `first name`= 'ChangedHJK' where id = 1;
END
|
DELIMITER ;
Execute and Verify Commands
CALL sample_sp_no_param;
select * from emp;
DELIMITER |
CREATE PROCEDURE sample_sp_with_params (IN empId INT UNSIGNED, OUT oldName VARCHAR(20), INOUT newName VARCHAR(20))
BEGIN
SELECT `first name` into oldName FROM emp where id = empId;
UPDATE emp SET `first name`= newName where id = empId;
END
|
DELIMITER ;
Execute and Verify Commands
set @inout='updatedHJK';
CALL sample_sp_with_params(1,@out,@inout);
select @out,@inout;
select * from emp;
DELIMITER |
CREATE PROCEDURE sample_sp_with_params_resultset (IN empId INT UNSIGNED, OUT oldName VARCHAR(20), INOUT newName VARCHAR(20))
BEGIN
SELECT `first name` into oldName FROM emp where id = empId;
UPDATE emp SET `first name`= newName where id = empId;
select * from emp;
END
|
DELIMITER ;
Execute and Verify Commands
set @inout='updatedHJKS';
CALL sample_sp_with_params_resultset (1,@out,@inout);
You can verify the values of OUT and INOUT parameters as:
select @out,@inout;
DELIMITER |
CREATE FUNCTION sample_fn_no_param ()
RETURNS INT
BEGIN
DECLARE count INT;
SELECT COUNT(*) INTO count FROM emp;
RETURN count;
END
|
DELIMITER ;
Execute and Verify Commands
select sample_fn_no_param ();
DELIMITER |
CREATE FUNCTION sample_fn_with_params (empId INT UNSIGNED, newName VARCHAR(20))
RETURNS VARCHAR(20)
BEGIN
DECLARE oldName VARCHAR(20);
SELECT `first name` into oldName FROM emp where id = empId;
UPDATE emp SET `first name`= newName where id = empId;
RETURN oldName;
END
|
DELIMITER ;
Execute and Verify Commands
select sample_fn_with_params(2,'UpdatedABC');
DROP PROCEDURE IF EXISTS sample_sp_no_param;
DROP PROCEDURE IF EXISTS sample_sp_with_params;
DROP PROCEDURE IF EXISTS sample_sp_with_params_resultset;
DROP FUNCTION IF EXISTS sample_fn_no_param;
DROP FUNCTION IF EXISTS sample_fn_with_params;