How to Declare a Variable in SQL Server?
Last Updated :
23 Aug, 2024
In SQL Server, variables play a critical role in the dynamic execution of SQL scripts and procedures. Variables allow you to store and manipulate data temporarily within the scope of a batch or procedure. By using the DECLARE
statement, you can create variables with specific data types, which can then be assigned values using the SET
or SELECT
commands.
In this article, We will learn about How to declare a variable in SQL Server by understanding various scenarios in detail.
How to Declare a Variable in SQL Server
To declare a variable in SQL Server, use the DECLARE statement. Variables must be prefixed with an @ symbol and must be assigned a data type.
Syntax:
DECLARE @VariableName DataType;
Example:
DECLARE @EmployeeID INT;
DECLARE @EmployeeName VARCHAR(100);
Assigning a Value to a Variable
After declaring a variable, we can assign a value to it using the SET or SELECT statement.
Using SET Command to Declare Variable in SQL Server
Syntax:
SET @VariableName = Value;
Example:
SET @EmployeeID = 1;
SET @EmployeeName = 'John Doe';
Using SELECT:
Syntax:
SELECT @VariableName = ColumnName FROM TableName WHERE Condition;
Example:
SELECT @EmployeeName = Name FROM Employees WHERE ID = @EmployeeID;
Using Variables in SQL Statements
Variables can be used in various SQL statements like SELECT, INSERT, UPDATE, and DELETE.
Example:
Update Statement:
UPDATE Employees
SET Name = @EmployeeName
WHERE ID = @EmployeeID;
Output:
Number of rows affected by the update operation.
Select Statement:
SELECT ID, Name FROM Employees WHERE ID = @EmployeeID;
Output:
Displays the ID and Name of the employee with the given @EmployeeID.
If @EmployeeID = 1 and Name = 'John Doe', the output would be:
Variable Scope and Lifetime
Scope: Local to batch, stored procedure, or function where declared. The variables are not accessible outside their declaring scope.
Lifetime: Till the end of the batch or procedure. The variable is not available any more after the execution is over.
Example:
BEGIN
DECLARE @TempVar INT;
SET @TempVar = 100;
-- @TempVar is accessible here
END;
-- @TempVar is not accessible here
Output:
No output outside the BEGIN...END block.
Using With Clause to Declare Variable in SQL Server
The WITH clause in SQL Server is primarily used for defining Common Table Expressions, which are temporary result sets that can be referenced in the SELECT, INSERT, UPDATE, or DELETE statement. That means the WITH clause will not be used to declare variables. Variables will be declared in SQL Server using the DECLARE statement.
Declaring and Using ariables in SQL Server
The example below shows how variables can be declared and used within SQL Server:
Variable Declaration:
DECLARE @MyVariable INT;
Assign a Value to the Variable:
SET @MyVariable = 10;
Use the Variable in a Query:
SELECT @MyVariable AS MyValue;
Example: Use Variable in a SELECT Statement
DECLARE @CustomerID INT;
SET @CustomerID = 1;
SELECT *
FROM Orders
WHERE CustomerID = @CustomerID;
CTE with the WITH Clause
The WITH clause is used for defining a temporary result set, known in this context as a common table expression (CTE), which you can then refer to within the execution of a single SQL statement.
Not for declaring variables, but quite handy in breaking down a complex query into manageable pieces.
Example of a CTE with the WITH Clause:
WITH SalesCTE AS (
SELECT SalesPersonID, SUM(TotalDue) AS TotalSales
FROM SalesOrderHeader
GROUP BY SalesPersonID
)
SELECT SalesPersonID, TotalSales
FROM SalesCTE
WHERE TotalSales > 100000;
Mixing Variables with CTEs
You can use both variables and CTEs in the same query, but they accomplish quite different things. Variables contain single scalar values whereas CTEs structure complex queries.
Example Mixing Variables and CTEs:
DECLARE @MinSales DECIMAL(10, 2);
SET @MinSales = 100000.00;
WITH SalesCTE AS (
SELECT SalesPersonID, SUM(TotalDue) AS TotalSales
FROM SalesOrderHeader
GROUP BY SalesPersonID
)
SELECT SalesPersonID, TotalSales
FROM SalesCTE
WHERE TotalSales > @MinSales:
Using Temporary Variables to Declare Variable in SQL Server
in SQL Server, when you refer to "temporary variables," you probably mean variables in the scope of one batch, stored procedure, or function. They are only those declared using the DECLARE statement and are temporary in terms of living only during the life of the batch or session.
Declaring and Using Temporary Variables
Declaring a Variable:
DECLARE @MyVariable INT;
- @MyVariable – Variable Name
- INT -- Data Type
Value Assignment to the Variable:
SET @MyVariable = 100;
This statement will assign a value 100 to the @MyVariable.
Using Variable:
SELECT @MyVariable AS MyValue;
It will return the value of the @MyVariable.
Example of Using a Temporary Variable in a Query
Suppose, you want the records based on a value to be stored in a variable:
DECLARE @CustomerID INT;
SET @CustomerID = 5;
SELECT *
FROM Orders
WHERE CustomerID = @CustomerID;
This example declares a variable @CustomerID and initializes it to a value of 5. The second step makes use of this variable together with the SELECT statement for filtering the records from the Orders table where CustomerID is equal to 5. Temporary Variables with Arithmetic or String Operations You can use variables for arithmetic or string operations: sql Copy code DECLARE @Price DECIMAL(10, 2); DECLARE @Quantity INT; DECLARE @Total DECIMAL(10, 2);
Using Subqueries to Declare Variable in SQL Server
We cannot declare a variable and directly assign it the result from a subquery in the DECLARE statement in SQL Server. However, we can set a variable with a subquery after it has been declared. This is often done with a SET or SELECT statement.
Example: Subquery with SET
DECLARE @TotalSales DECIMAL(10, 2);
SET @TotalSales = (SELECT SUM(TotalAmount) FROM Orders WHERE CustomerID = 1);
SELECT @TotalSales AS TotalSalesForCustomer;
In this example:
- A variable @TotalSales is declared.
- The SET statement assigns the result of a subquery – that calculates the total sales for a particular customer – to the variable.
- The content stored in @TotalSales is then selected and returned.
Example: Using a Subquery with SELECT
DECLARE @HighestPrice DECIMAL(10, 2);
SELECT @HighestPrice = (SELECT MAX(UnitPrice) FROM Products);=
SELECT @HighestPrice AS HighestProductPrice;
In this example:
- A variable @HighestPrice is declared.
- The SELECT statement simply assigns the result of a subquery, which finds the highest price for a product, to the variable. It then selects and returns this value stored in @HighestPrice.
Common Data Types
SQL Server supports various data types for variables:
- INT: Integer values
- VARCHAR(n): Variable-length character strings
- CHAR(n): Fixed-length character strings
- DATE: Dates
- FLOAT: Floating-point numbers
Conclusion
Variable declaration in SQL Server is an essential requirement to handle and process data efficiently in SQL scripts, stored procedures, and functions. Variables can be declared by using the DECLARE statement and then values set to them by SET or SELECT statements. The functioning or operation of temporary data, logic flow control, and execution of complicated queries can be performed in a better way. In order to manipulate variables, you must understand their scope of operation and lifetime. Variable declaration, in general, greatly enhances the capability of writing dynamic SQL code for efficiency, hence robust and manageable database applications.
Similar Reads
How to Declare a Variable in SQL?
Variables in SQL are fundamental for building efficient and scalable database applications. They enhance the flexibility and efficiency of database queries by acting as placeholders for data. Understanding how to declare and use variables in SQL is crucial for writing dynamic and effective queries I
3 min read
How to Declare a Variable in PL/SQL?
Declaring variables in PL/SQL is a fundamental step towards building powerful and efficient database applications. Variables act as placeholders for data which enable us to manipulate and store information within our PL/SQL programs. Here, we will explore various methods of declaring variables in PL
5 min read
How to Declare a Variable in SQLite?
Declaring variables in SQLite can greatly enhance the flexibility and efficiency of our database queries. Whether we need to store temporary values, simplify complex operations or reuse values within a query, understanding how to declare variables in SQLite is very important. In this article, we'll
3 min read
CREATE TABLE in SQL Server
SQL Server provides a variety of data management tools such as querying, indexing, and transaction processing. It supports multiple programming languages and platforms, making it a versatile RDBMS for various applications. With its robust features and reliability, SQL Server is a popular choice for
4 min read
SQL Server SELECT INTO @Variable
In the world of SQL Server, the SELECT INTO statement is a powerful syntax for retrieving data from one or more tables and inserting it into a new table. However, what if you want to store the result set of a SELECT query into a variable rather than a table? This is where the SELECT INTO @Variable s
6 min read
How to Open a Database in SQL Server?
Opening a database in SQL Server is a fundamental task for database administrators and developers. It involves establishing a connection to the server instance and selecting a database to work with. In this article, we will explore two methods to open a database in SQL Server such as using SQL Serve
3 min read
SQL Server Describe Table
SQL Server is a widely used Relational Database Management System (RDBMS) that allows users to create and manage databases effectively. When working with databases in SQL Server it is essential to understand the schema of the tables present in the database. Describing a table means getting informati
4 min read
Dynamic Table Name Variable in SQL Server
In SQL Server, the dynamic table name variable is used when the name of the table is not explicitly stated in a query but is set in a variable and used instead. This can be in situations where the user does not know or the executing code does not know the table name beforehand and is only determined
3 min read
How to write a SQL query in R?
In this article, we are going to learn how to write SQL queries in the R programming language. What is SQL Query? SQL stands for Structured Query Language. SQL queries are used for interacting with a database. Using SQL queries we can access and manipulate data stored in the database. With the help
4 min read
How to Escape a Single Quote in SQL Server?
SQL stands for structured query language and is used to query databases for analytical needs. While using arithmetic queries, some results require strings to help them understand better. Strings can be formed by enclosing text in quotes. However in a case when quotes are themselves required in a str
4 min read