SQL Stored Procedures π€ΒΆ
Prerequisites: SQL Commands, INSERT/UPDATE Statements
Mentor's Note: Think of a Stored Procedure like a "Microwave Preset". Instead of manually setting the power and time every time you want to pop popcorn, you just press one button. A Stored Procedure saves a complex script so you can "play" it again with a single command. π‘
π The Scenario: The Daily Backup πΒΆ
Imagine you have to move all "Cancelled Orders" to a "History" table every night.
- Manual: Write 5 different queries every night. (Exhausting! π₯΅)
- Procedure: Write the logic once, save it as archive_orders(), and just call it. β
π» 1. The Basic SyntaxΒΆ
π» 2. Using Parameters (Inputs) π₯ΒΆ
You can pass data into a procedure to make it dynamic.
-- Scenario: Create a procedure to give a specific employee a raise
CREATE PROCEDURE GiveRaise (IN emp_id INT, IN raise_amt DECIMAL)
BEGIN
UPDATE employees
SET salary = salary + raise_amt
WHERE id = emp_id;
END;
-- To Run:
CALL GiveRaise(101, 5000);
π¨ Visual Logic: The Black BoxΒΆ
graph LR
A[Input Parameters π₯] --> B[Stored Procedure βοΈ]
B -- "Executes Script" --> C[(Database ποΈ)]
C -- "Returns Status/Data" --> B
B --> D[Output Result π€]
π Why use Stored Procedures?ΒΆ
- Efficiency: The code is compiled once and runs faster. β‘
- Security: You can let users "Run the Procedure" without giving them access to the "Raw Tables". π‘οΈ
- Consistency: Ensures the exact same math is used by every app (Web, Mobile, Admin).