โ
Stored Procedures ๐ฏ
๐ง 1. What is a Stored Procedure?
A Stored Procedure is a saved SQL program
โข Stored inside the database
โข Can be executed anytime
Think like this ๐
โReusable SQL code blockโ
โก 2. Why Use Stored Procedures?
โข Reuse SQL logic
โข Reduce repeated code
โข Better security
โข Faster execution for repeated tasks
โก 3. Basic Syntax
๐ MySQL Example:
DELIMITER //
CREATE PROCEDURE GetEmployees()
BEGIN
SELECT * FROM employees;
END //
DELIMITER ;
โถ๏ธ 4. Execute Stored Procedure
CALL GetEmployees();
๐ฅ 5. Procedure with Parameter
DELIMITER //
CREATE PROCEDURE GetDeptEmployees(IN dept_name VARCHAR(50))
BEGIN
SELECT * FROM employees
WHERE department = dept_name;
END //
DELIMITER ;
โถ๏ธ 6. Execute Parameterized Procedure
CALL GetDeptEmployees('IT');
โ 7. Drop Stored Procedure
DROP PROCEDURE GetEmployees;
๐ฏ 8. Real Example
Increase salary for all IT employees:
DELIMITER //
CREATE PROCEDURE IncreaseSalary()
BEGIN
UPDATE employees
SET salary = salary + 5000
WHERE department = 'IT';
END //
DELIMITER ;
๐ฏ 9. Practice Tasks
1. Create procedure to show all employees
2. Create procedure for HR employees
3. Create procedure with salary parameter
4. Execute stored procedure
5. Drop procedure
โก Mini Challenge ๐ฅ
Create procedure to return employees with salary > given value
โ
Solution
DELIMITER //
CREATE PROCEDURE GetHighSalaryEmployees(IN min_salary INT)
BEGIN
SELECT *
FROM employees
WHERE salary > min_salary;
END //
DELIMITER ;
โถ๏ธ Execute Procedure
CALL GetHighSalaryEmployees(50000);
โ Returns employees earning more than 50k
Key Difference:
โข Function โ returns value
โข Procedure โ performs action / multiple operations
Double Tap โค๏ธ For More
Post #2436
3.03K
- โค 7