100 Days of SQL


Day 27 – SQL Stored Procedures

SQL stored procedures are a type of program stored in a database that can be executed on demand. A stored procedure is a precompiled set of one or more SQL statements that are stored in the database and can be called repeatedly by client applications or other database objects.

Stored procedures can be used to simplify complex SQL operations, improve performance, and provide a layer of abstraction between client applications and the database. They can also be used to enforce security, encapsulate business rules, and provide a standard interface for interacting with the database.

Here’s an example of how to create a stored procedure in SQL:

CREATE PROCEDURE get_customer_orders
    @customer_id int
    SELECT order_id, order_date, order_amount
    FROM orders
    WHERE customer_id = @customer_id
    ORDER BY order_date DESC;

In this example, we create a stored procedure named “get_customer_orders” that accepts a parameter named “@customer_id” and returns the order details for that customer. When executed, the stored procedure will run the SQL SELECT statement and return the results.

Once the stored procedure is created, it can be executed by calling its name and passing in the required parameter:

EXEC get_customer_orders @customer_id = 12345;

In this example, we execute the “get_customer_orders” stored procedure and pass in the value “12345” for the “@customer_id” parameter. The stored procedure will then return the order details for the specified customer.