Skip to content

Commit ed91337

Browse files
authored
Refresh variables article and fix examples (UUF 548092) (#36503)
1 parent 8e8dd6e commit ed91337

1 file changed

Lines changed: 73 additions & 67 deletions

File tree

docs/t-sql/language-elements/variables-transact-sql.md

Lines changed: 73 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ title: "Variables (Transact-SQL)"
33
description: A Transact-SQL local variable is an object that can hold a single data value of a specific type.
44
author: rwestMSFT
55
ms.author: randolphwest
6-
ms.date: 07/08/2024
6+
ms.date: 01/28/2026
77
ms.service: sql
88
ms.subservice: t-sql
99
ms.topic: reference
@@ -17,137 +17,147 @@ monikerRange: ">=aps-pdw-2016 || =azuresqldb-current || =azure-sqldw-latest || >
1717

1818
[!INCLUDE [sql-asdb-asdbmi-asa-pdw-fabricse-fabricdw-fabricsqldb](../../includes/applies-to-version/sql-asdb-asdbmi-asa-pdw-fabricse-fabricdw-fabricsqldb.md)]
1919

20-
A Transact-SQL local variable is an object that can hold a single data value of a specific type. Variables in batches and scripts are typically used:
20+
A Transact-SQL local variable is an object that can hold a single data value of a specific type. You typically use variables in batches and scripts for the following purposes:
2121

22-
- As a counter either to count the number of times a loop is performed, or to control how many times the loop is performed.
23-
- To hold a data value to be tested by a control-of-flow statement.
24-
- To save a data value to be returned by a stored procedure return code or function return value.
22+
- Use a variable as a counter to count the number of times a loop is performed, or to control how many times the loop is performed.
23+
- Hold a data value to test by a control-of-flow statement.
24+
- Save a data value to return by a stored procedure return code or function return value.
25+
26+
[!INCLUDE [article-uses-adventureworks](../../includes/article-uses-adventureworks.md)]
2527

2628
## Remarks
2729

28-
The names of some Transact-SQL system functions begin with two *at* signs (`@@`). Although in earlier versions of [!INCLUDE [ssNoVersion](../../includes/ssnoversion-md.md)], the `@@` functions are referred to as global variables, `@@` functions aren't variables, and they don't have the same behaviors as variables. The `@@` functions are system functions, and their syntax usage follows the rules for functions.
30+
The names of some Transact-SQL system functions begin with two *at* signs (`@@`). Although earlier versions of [!INCLUDE [ssNoVersion](../../includes/ssnoversion-md.md)] refer to the `@@` functions as global variables, `@@` functions aren't variables, and they don't have the same behaviors as variables. The `@@` functions are system functions, and their syntax usage follows the rules for functions.
2931

3032
You can't use variables in a view.
3133

3234
Changes to variables aren't affected by the rollback of a transaction.
3335

3436
## Declare a Transact-SQL variable
3537

36-
The `DECLARE` statement initializes a Transact-SQL variable by:
38+
Use the `DECLARE` statement to initialize a Transact-SQL variable by:
3739

38-
- Assigning a name. The name must have a single `@` as the first character.
40+
- Assigning a name. The name must start with a single `@` character.
3941

40-
- Assigning a system-supplied or user-defined data type and a length. For numeric variables, a precision and scale are also assigned. For variables of type XML, an optional schema collection might be assigned.
42+
- Assigning a system-supplied or user-defined data type and a length. For numeric variables, you can assign a precision and optional scale. For variables of type XML, you can optionally assign a schema collection.
4143

4244
- Setting the value to `NULL`.
4345

4446
For example, the following `DECLARE` statement creates a local variable named `@mycounter` with an **int** data type. By default, the value for this variable is `NULL`.
4547

4648
```sql
47-
DECLARE @MyCounter INT;
49+
DECLARE @MyCounter AS INT;
4850
```
4951

50-
To declare more than one local variable, use a comma after the first local variable defined, and then specify the next local variable name and data type.
52+
To declare more than one local variable, use a comma after the first local variable definition, and then specify the next local variable name and data type.
5153

52-
For example, the following `DECLARE` statement creates three local variables named `@LastName`, `@FirstName` and `@StateProvince`, and initializes each to `NULL`:
54+
For example, the following `DECLARE` statement creates three local variables named `@LastName`, `@FirstName`, and `@StateProvince`, and initializes each to `NULL`:
5355

5456
```sql
55-
DECLARE @LastName NVARCHAR(30), @FirstName NVARCHAR(20), @StateProvince NCHAR(2);
57+
DECLARE @LastName AS NVARCHAR (30),
58+
@FirstName AS NVARCHAR (20),
59+
@StateProvince AS NCHAR (2);
5660
```
5761

5862
In another example, the following `DECLARE` statement creates a Boolean variable called `@IsActive`, which is declared as **bit** with a value of `0` (`false`):
5963

6064
```sql
61-
DECLARE @IsActive BIT = 0;
65+
DECLARE @IsActive AS BIT = 0;
6266
```
6367

6468
## Variable scope
6569

6670
The scope of a variable is the range of Transact-SQL statements that can reference the variable. The scope of a variable lasts from the point it's declared until the end of the batch or stored procedure in which it's declared. For example, the following script generates a syntax error because the variable is declared in one batch (separated by the `GO` keyword) and referenced in another:
6771

6872
```sql
69-
USE AdventureWorks2022;
73+
USE AdventureWorks2025;
7074
GO
7175

72-
DECLARE @MyVariable INT;
73-
76+
DECLARE @MyVariable AS INT;
7477
SET @MyVariable = 1;
75-
GO
7678

7779
SELECT BusinessEntityID,
78-
NationalIDNumber,
79-
JobTitle
80+
NationalIDNumber,
81+
JobTitle
8082
FROM HumanResources.Employee
8183
WHERE BusinessEntityID = @MyVariable;
8284
```
8385

84-
Variables have local scope and are only visible within the batch or procedure where they're defined. In the following example, the nested scope created for execution of `sp_executesql` doesn't have access to the variable declared in the higher scope and returns and error.
86+
Variables have local scope and are only visible within the batch or procedure where you define them. In the following example, the nested scope created for execution of `sp_executesql` doesn't have access to the variable declared in the higher scope and returns an error.
8587

8688
```sql
87-
DECLARE @MyVariable INT;
89+
DECLARE @MyVariable AS INT;
8890
SET @MyVariable = 1;
89-
EXECUTE sp_executesql N'SELECT @MyVariable'; -- this produces an error
91+
92+
EXECUTE sp_executesql N'SELECT @MyVariable';
93+
```
94+
95+
This query produces the following error:
96+
97+
```output
98+
Msg 137, Level 15, State 2, Line 1
99+
Must declare the scalar variable "@MyVariable".
90100
```
91101

92102
## Set a value in a Transact-SQL variable
93103

94-
When a variable is first declared, its value is set to `NULL`. To assign a value to a variable, use the `SET` statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a `SELECT` statement.
104+
When you first declare a variable, its value is `NULL`. To assign a value to a variable, use the `SET` statement. This method is the preferred way to assign a value to a variable. You can also assign a value to a variable by referencing it in the select list of a `SELECT` statement.
95105

96-
To assign a variable a value by using the SET statement, include the variable name and the value to assign to the variable. This is the preferred method of assigning a value to a variable. The following batch, for example, declares two variables, assigns values to them, and then uses them in the `WHERE` clause of a `SELECT` statement:
106+
To assign a variable a value by using the `SET` statement, include the variable name and the value to assign to the variable. This method is the preferred way to assign a value to a variable. The following batch, for example, declares two variables, assigns values to them, and then uses them in the `WHERE` clause of a `SELECT` statement:
97107

98108
```sql
99-
USE AdventureWorks2022;
109+
USE AdventureWorks2025;
100110
GO
101111

102112
-- Declare two variables.
103-
DECLARE @FirstNameVariable NVARCHAR(50),
104-
@PostalCodeVariable NVARCHAR(15);
113+
DECLARE @FirstNameVariable AS NVARCHAR (50),
114+
@PostalCodeVariable AS NVARCHAR (15);
105115

106116
-- Set their values.
107117
SET @FirstNameVariable = N'Amy';
108118
SET @PostalCodeVariable = N'BA5 3HX';
109119

110120
-- Use them in the WHERE clause of a SELECT statement.
111121
SELECT LastName,
112-
FirstName,
113-
JobTitle,
114-
City,
115-
StateProvinceName,
116-
CountryRegionName
122+
FirstName,
123+
JobTitle,
124+
City,
125+
PostalCode,
126+
StateProvinceName,
127+
CountryRegionName
117128
FROM HumanResources.vEmployee
118129
WHERE FirstName = @FirstNameVariable
119-
OR PostalCode = @PostalCodeVariable;
120-
GO
130+
OR PostalCode = @PostalCodeVariable;
121131
```
122132

123-
A variable can also have a value assigned by being referenced in a select list. If a variable is referenced in a select list, it should be assigned a scalar value or the `SELECT` statement should only return one row. For example:
133+
You can also assign a value to a variable by referencing it in a select list. If you reference a variable in a select list, assign it a scalar value or ensure the `SELECT` statement returns only one row. For example:
124134

125135
```sql
126-
USE AdventureWorks2022;
136+
USE AdventureWorks2025;
127137
GO
128-
DECLARE @EmpIDVariable INT;
129138

130-
SELECT @EmpIDVariable = MAX(EmployeeID)
139+
DECLARE @EmpIDVariable AS INT;
140+
141+
SELECT @EmpIDVariable = MAX(BusinessEntityID)
131142
FROM HumanResources.Employee;
132-
GO
133143
```
134144

135145
> [!WARNING]
136-
> If there are multiple assignment clauses in a single `SELECT` statement, [!INCLUDE [ssnoversion-md](../../includes/ssnoversion-md.md)] doesn't guarantee the order of evaluation of the expressions. Effects are only visible if there are references among the assignments.
146+
> If there are multiple assignment clauses in a single `SELECT` statement, the [!INCLUDE [ssde-md](../../includes/ssde-md.md)] doesn't guarantee the order of evaluation of the expressions. Effects are only visible if there are references among the assignments.
137147
138148
If a `SELECT` statement returns more than one row and the variable references a nonscalar expression, the variable is set to the value returned for the expression in the last row of the result set. For example, in the following batch `@EmpIDVariable` is set to the `BusinessEntityID` value of the last row returned, which is `1`:
139149

140150
```sql
141-
USE AdventureWorks2022;
151+
USE AdventureWorks2025;
142152
GO
143-
DECLARE @EmpIDVariable INT;
153+
154+
DECLARE @EmpIDVariable AS INT;
144155

145156
SELECT @EmpIDVariable = BusinessEntityID
146157
FROM HumanResources.Employee
147158
ORDER BY BusinessEntityID DESC;
148159

149160
SELECT @EmpIDVariable;
150-
GO
151161
```
152162

153163
## Examples
@@ -156,54 +166,50 @@ The following script creates a small test table and populates it with 26 rows. T
156166

157167
- Control how many rows are inserted by controlling how many times the loop is executed.
158168
- Supply the value inserted into the integer column.
159-
- Function as part of the expression that generates letters to be inserted into the character column.
169+
- Function as part of the expression that generates letters to insert into the character column.
160170

161171
```sql
162172
-- Create the table.
163-
CREATE TABLE TestTable (cola INT, colb CHAR(3));
164-
GO
173+
CREATE TABLE TestTable
174+
(
175+
cola INT,
176+
colb CHAR (3)
177+
);
165178

166179
SET NOCOUNT ON;
167-
GO
168180

169181
-- Declare the variable to be used.
170-
DECLARE @MyCounter INT;
182+
DECLARE @MyCounter AS INT;
171183

172184
-- Initialize the variable.
173185
SET @MyCounter = 0;
174186

175187
-- Test the variable to see if the loop is finished.
176188
WHILE (@MyCounter < 26)
177-
BEGIN;
178189
-- Insert a row into the table.
179-
INSERT INTO TestTable
180-
VALUES
190+
BEGIN
191+
INSERT INTO TestTable
181192
-- Use the variable to provide the integer value
182193
-- for cola. Also use it to generate a unique letter
183194
-- for each row. Use the ASCII function to get the
184195
-- integer value of 'a'. Add @MyCounter. Use CHAR to
185196
-- convert the sum back to the character @MyCounter
186197
-- characters after 'a'.
187-
(
188-
@MyCounter,
189-
CHAR((@MyCounter + ASCII('a')))
198+
VALUES (
199+
@MyCounter,
200+
CHAR((@MyCounter + ASCII('a')))
190201
);
191-
192-
-- Increment the variable to count this iteration
193-
-- of the loop.
194-
SET @MyCounter = @MyCounter + 1;
195-
END;
196-
GO
197-
202+
-- Increment the variable to count this iteration
203+
-- of the loop.
204+
SET @MyCounter = @MyCounter + 1;
205+
END
198206
SET NOCOUNT OFF;
199-
GO
200207

201208
-- View the data.
202-
SELECT cola, colb FROM TestTable;
203-
GO
204-
209+
SELECT cola,
210+
colb
211+
FROM TestTable;
205212
DROP TABLE TestTable;
206-
GO
207213
```
208214

209215
## Related content

0 commit comments

Comments
 (0)