Careeroza
Stored Procedures
What is a Stored Procedure?
A stored procedure is prepared SQL code saved in the database under a name, so it can be called again and again. It can contain several statements, variables, conditions, loops and error handling.
- One round trip to the server instead of many.
- Business rules live in one place for every application.
- Users can be allowed to
EXECUTEthe procedure without direct access to the tables.
Note: SQLite does not support stored procedures, so the examples on this page are for MySQL, SQL Server and PostgreSQL.
MySQL
DELIMITER //
CREATE PROCEDURE GetCustomersByCountry(IN p_country VARCHAR(50))
BEGIN
SELECT CustomerID, CustomerName, City
FROM Customers
WHERE Country = p_country
ORDER BY CustomerName;
END //
DELIMITER ;
CALL GetCustomersByCountry('India');DELIMITER changes the statement terminator so the ; inside the body does not end the CREATE early.
SQL Server
CREATE PROCEDURE dbo.GetCustomersByCountry
@Country NVARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
SELECT CustomerID, CustomerName, City
FROM Customers
WHERE Country = @Country;
END;
GO
EXEC dbo.GetCustomersByCountry @Country = 'India';PostgreSQL
-- PostgreSQL 11+: procedures (can COMMIT inside); use functions to return rows
CREATE PROCEDURE archive_old_orders(p_before DATE)
LANGUAGE plpgsql
AS $$
BEGIN
INSERT INTO OrdersArchive SELECT * FROM Orders WHERE OrderDate < p_before;
DELETE FROM Orders WHERE OrderDate < p_before;
END;
$$;
CALL archive_old_orders('2024-01-01');