HOW TO USE VARIABLES IN STORED PROCEDURES

In stored procedures, variables are used to store and manipulate data within the procedure. It is a placeholder to store data in memory.

In real time, we often have situations where we need to run a procedure frequently. It is not a good practice to open the procedure everytime and change the conditions of the query. So, we need to use variables.

The syntax might vary depending of the database. In MSSQL Server, we can use the following way to use variable inside stored procedure.

Syntax:

  • @VariableName is the name of the variable.
  • DataType is the data type of the variable (e.g., INT, VARCHAR, etc.).
  • SET is used to assign a value to the variable.
  • You can then use the variable in your SQL queries.

For MySQL, the syntax is similar:

For PostgreSQL:

Remember to replace DataType, VariableName, TableName, and ColumnName with your actual data types, variable names, table names, and column names. If you’re using a specific DBMS, it’s always a good idea to refer to its documentation for the exact syntax and rules.

Real time use case:

Now the fun part, Let’s put into practice this concept of using variables inside a stored procedure.

Step 1: Source

For practice, I use the AdventureWorks2019 database and [Production].[WorkOrder] table.

Step 2: Example Scenario and Query

Lets say that we need to know the count of Stocks that are due in the year 2011

The SQL to get this requirement is,

The above query produces the following result

Step 3: Use Variables

Now, instead of hardcoding the dates, we can use variables for the start and end dates.

Step 4: Create procedure and pass variable as parameter

To further make it reusable, we can put the query inside a stored procedure and pass the variable as parameter.

To execute the procedure, we should use EXEC command as follows,

Executing the procedure will give us the same result as the SQL query

Conclusion:-

We can write a simple SQL, but applying the best practices by using variables and procedures saves us time for subsequent and frequent runs.

It is also easier to make changes in one place, rather to update values in multiple queries, which can cause errors.

Popular posts