Stored Procedure in SQL

A precompiled set of SQL statements and procedural logic is known as a stored procedure in SQL, and it can be stored in a database and repeatedly performed. It is a named collection of control-of-flow and SQL statements that can conduct actions, return values, and receive input arguments. Stored procedures can be invoked by other database objects or applications, and they are frequently used to encapsulate and reuse database functionality.

The SQL CREATE PROCEDURE statement, which enables the specification of input parameters, output parameters, a body of SQL statements, and procedural logic, is used to create stored procedures. The EXECUTE and CALL commands can be used to run stored procedures after they have been created. The ALTER PROCEDURE and DROP PROCEDURE statements can be used to change or remove stored procedures. It may also contain error-handling code and flow-controlling clauses like IF/ELSE and WHILE loops. The SELECT, INSERT, UPDATE, and DELETE SQL statements as well as external programs that use APIs like ODBC, JDBC, or ADO.NET can all call stored procedures.

Benefits of using stored procedures include:

  1. Reusability: By allowing reuse across numerous applications and database objects, stored procedures eliminate the need to repeatedly write and test the same code.

  2. Improved performance:

    Ad hoc SQL statements take longer to run than stored procedures because they are not only precompiled but also stored in memory.
  3. Enhanced security: Access to sensitive data can be restricted by granting stored procedures rights to particular users or roles.

  4. Simplified maintenance: Because stored procedures include database logic, they may be updated or changed without affecting the applications that use them, making maintenance easier and lowering the possibility of mistakes.

    Here is an illustration of a fundamental stored procedure that takes a parameter as input and returns a result set:

CREATE PROCEDURE get_customers_by_city(@city VARCHAR(50)) AS BEGIN SELECT customer_id, customer_name, city FROM customers WHERE city = @city; END

The "get_customers_by_city" stored procedure filters the results of a SELECT query using a single input parameter called "@city" that it accepts. A result set including the customer ID, name, and city for each and every customer in the chosen city is returned by the stored process. Use the following syntax to run this stored procedure:

EXEC get_customers_by_city 'New Delhi';

By doing this, the stored procedure would be called, and a result set containing all of the city of New Delhi's clients would be returned. Keep in mind that depending on the individual SQL database system being used, the precise syntax for generating and running stored procedures may change. For additional information, visit the system documentation.


In SQL, there are two types of stored procedures:

  1. System stored procedures: The SQL database system itself offers these pre-defined stored procedures. They carry out particular system-level operations including establishing or deleting databases, retrieving system data, or controlling security settings. Database administrators often employ system stored procedures, which are not designed to be altered or customized by end users.

  2. User-defined stored procedures: Users developed these stored procedures to carry out particular application-level activities. User-defined stored procedures can be modified to fit particular business needs and can be used again by different applications. They can incorporate flow control statements and error handling code, accept input parameters, and return output values.

User-defined stored procedures can be further classified into three types based on their functionality:

  • Data access stored procedures: Data from a database can be retrieved, added, updated, or deleted using these stored procedures. They are frequently used to encapsulate intricate business logic, and by lowering network traffic, they can boost performance.

  • Utility stored procedures: These stored procedures are used to carry out useful tasks like creating reports, sending emails, and making backups. Other stored procedures or application code frequently invoke them.

  • System stored procedures: Users develop these stored procedures to communicate with the system stored procedures made available by the SQL database system. They are used to control security parameters, get system data, or carry out other system-level operations.


Depending on the particular requirements of the application or business process, stored procedures can be utilized in a variety of SQL circumstances. The following are a few typical situations where stored processes may be helpful:

  1. Repeated operations: A stored procedure can save time by preventing the need to repeat writing the same code if you frequently conduct the same database operation, such as inserting or modifying data.

  2. Complex operations: A stored procedure can be used to encapsulate the logic and make a multi-step, complex database activity easier to administer and maintain. Reduced network traffic and fewer round trips between the database and the application can both boost performance.

  3. Security: In order to manage security, stored procedures can restrict access to database objects and data. You can restrict direct access to tables and views as well as the actions that can be taken with the data by establishing stored procedures to access it.

  4. Modularity: Modularizing stored routines into smaller pieces of code helps facilitate testing and debugging. Additionally, this may make it simpler to maintain and upgrade the code in the future.

  5. Maintenance: Tasks like backups, restorations, and upgrades can be made easier with the help of stored procedures. It is possible to guarantee that these actions are carried out consistently and dependably by building stored procedures to carry them out.

Keep in mind that the choice to employ stored procedures should be made based on the particular needs of the application or business process. In other circumstances, stored procedures might not be required or might even add needless complexity. Before selecting whether to employ stored procedures or not, it is crucial to consider their potential advantages and disadvantages.

Here's another example of a stored procedure that inserts data into a table:

CREATE PROCEDURE insert_customer( @customer_name VARCHAR(50), @city VARCHAR(50), @country VARCHAR(50) ) AS BEGIN INSERT INTO customers (customer_name, city, country) VALUES (@customer_name, @city, @country); END

This stored procedure is called "insert_customer" and accepts three input parameters: "@customer_name", "@city", and "@country". The stored procedure inserts a new row into the "customers" table with the specified values.

To execute this stored procedure, use the following syntax:

EXEC insert_customer 'XYZ Ltd', 'New Delhi', 'India';

This would execute the stored procedure and insert a new row into the "customers" table with the values 'XYZ Ltd', 'New Delhi'', 'India'.


Exercises for creating and using stored procedures in SQL:

  1. Create a stored procedure that accepts a customer ID as input and returns the customer's name, email address, and order history.

CREATE PROCEDURE get_customer_info @customer_id int AS BEGIN SELECT c.customer_name, c.email_address, o.order_date, o.order_total FROM customers c INNER JOIN orders o ON c.customer_id = o.customer_id WHERE c.customer_id = @customer_id END

To execute this stored procedure, use the following syntax:

EXEC get_customer_info 1234;

This would execute the stored procedure and return the customer information for the customer with ID 1234.

  1. Create a stored procedure that accepts a product ID as input and returns the product name, category, and inventory level.

CREATE PROCEDURE get_product_info @product_id int AS BEGIN SELECT p.product_name, pc.category_name, pi.inventory_level FROM products p INNER JOIN product_categories pc ON p.category_id = pc.category_id INNER JOIN product_inventory pi ON p.product_id = pi.product_id WHERE p.product_id = @product_id END

To execute this stored procedure, use the following syntax:

EXEC get_product_info 5678;

This would execute the stored procedure and return the product information for the product with ID 5678.

  1. Create a stored procedure that accepts a date range as input and returns the total sales for each day in the range.

CREATE PROCEDURE get_sales_by_day @start_date date, @end_date date AS BEGIN SELECT order_date, SUM(order_total) as total_sales FROM orders WHERE order_date >= @start_date AND order_date <= @end_date GROUP BY order_date END

To execute this stored procedure, use the following syntax:

EXEC get_sales_by_day '2022-01-01', '2022-01-31';

This would execute the stored procedure and return the total sales for each day in January 2022.

Comments

Popular posts from this blog

OWASP Top 10

TCP/IP Model

AAA