Welcome to CodeYourCraft's SQL EXECUTE Procedure tutorial! This lesson is designed for both beginners and intermediates, so let's get started. š
A SQL Procedure (or stored procedure) is a prepared SQL code that you can save, use multiple times, and parameterize. They are essential for automating repetitive database tasks, improving performance, and enforcing data consistency. š” Pro Tip: Procedures can be written in SQL or a procedural language supported by the database system.
Let's create a simple SQL procedure that inserts a record into our employees table.
CREATE PROCEDURE AddEmployee (
IN first_name VARCHAR(50),
IN last_name VARCHAR(50),
IN email VARCHAR(100)
)
BEGIN
INSERT INTO employees (first_name, last_name, email)
VALUES (first_name, last_name, email);
END;š Note: The CREATE PROCEDURE statement defines a new procedure, specifying its name, parameters, and the SQL code to be executed. The BEGIN and END keywords mark the start and end of the procedure's code block.
To run the AddEmployee procedure, use the CALL statement followed by the procedure name and its parameters enclosed in parentheses.
CALL AddEmployee('John', 'Doe', 'john.doe@example.com');This command creates a new row in the employees table with the provided first name, last name, and email.
What is the purpose of a SQL Procedure?
Now, let's explore more complex examples that demonstrate the power and versatility of SQL procedures.
A common use case for SQL procedures is to generate reports. Here's an example that calculates the total sales for a specific period.
CREATE PROCEDURE GetTotalSales (
IN start_date DATE,
IN end_date DATE
)
BEGIN
SELECT SUM(sales) AS total_sales
FROM sales
WHERE sale_date BETWEEN start_date AND end_date;
END;To use this procedure, call it with the desired date range:
CALL GetTotalSales('2021-01-01', '2021-12-31');This example demonstrates the use of conditional logic in a stored procedure. It calculates the discount for a customer based on their total purchases.
CREATE PROCEDURE CalculateDiscount (
IN total_purchases DECIMAL(10, 2)
)
BEGIN
DECLARE discount DECIMAL(5, 2);
IF total_purchases > 1000 THEN
SET discount = 0.15;
ELSEIF total_purchases > 500 THEN
SET discount = 0.10;
ELSE
SET discount = 0.05;
END IF;
SELECT CONCAT('You have a discount of ', discount * 100, '%') AS discount;
END;To use this procedure, call it with the customer's total purchases:
CALL CalculateDiscount(1200);This procedure will return the discount percentage for the customer with a total purchase of 1200.
Which SQL statement defines a new procedure?
SQL Procedures are essential tools for any developer looking to automate repetitive tasks, improve database performance, and enforce data consistency. By learning to create and use procedures, you'll be well-equipped to tackle a wide range of real-world programming challenges. Happy coding! š” Pro Tip: Be sure to test your SQL procedures thoroughly and consider using version control to manage your codebase.