Stored Procedures In SQL


Definition of stored procedure

A stored procedure is a pre-compiled and reusable database object that contains a set of SQL statements and procedural code. It can be called by other programs, applications or stored procedures to execute the stored code. Stored procedures can be used to perform common database operations, such as inserting, updating, deleting, and retrieving data, and they can also be used to implement business logic and other complex operations. 

Steps to create a stored procedure 

You can create a stored procedure using the CREATE PROCEDURE statement. Here’s a basic syntax for creating a stored procedure: 

For example, let’s create a stored procedure that retrieves all customers from a customer table: 

Procedure to modify an existing stored procedure 

  • You can modify an existing stored procedure using the ALTER PROCEDURE statement. Here’s a basic syntax for modifying a stored procedure: 

For example, let’s modify the GetCustomers stored procedure to retrieve customers only from a specific city: 

How to drop a stored procedure 

You can drop an existing stored procedure using the DROP PROCEDURE statement. Here’s a basic syntax for dropping a stored procedure: 

For example, let’s drop the GetCustomers stored procedure: 

Three types of parameters in stored procedure: input, output, and input/output 

There are three types of parameters that can be used in a stored procedure: 

  • Input Parameters: These parameters are used to pass values into the stored procedure. They are declared using the @ symbol followed by the parameter name and data type. 
  • Output Parameters: These parameters are used to return values from the stored procedure. They are declared using the OUTPUT keyword before the parameter name. 
  • Input/Output Parameters: These parameters are used to pass values into the stored procedure and also return values from the stored procedure. They are declared using the INOUT keyword before the parameter name. 

The way to pass parameters in a stored procedure 

  • You can pass parameters to a stored procedure when you call it. Here’s a basic syntax for calling a stored procedure with parameters: 
  • You can pass parameters to a stored procedure when you call it. Here’s a basic syntax for calling a stored  
  • procedure with parameters: 

For example, let’s call the modified GetCustomers stored procedure with a parameter: 

  • How to encrypt a stored procedure for security purposes 

You can encrypt a stored procedure using the WITH ENCRYPTION clause. This will prevent anyone from viewing the code of the stored procedure. Here’s a basic syntax for encrypting a stored procedure: 

For example, let’s create an encrypted version of the GetCustomers stored procedure: 

Note that once a stored procedure is encrypted, you cannot modify it or view its code. So make sure you have a backup copy of the original code before encrypting it. 

Types Of Stored Procedures