You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
21
21
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.
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.
29
31
30
32
You can't use variables in a view.
31
33
32
34
Changes to variables aren't affected by the rollback of a transaction.
33
35
34
36
## Declare a Transact-SQL variable
35
37
36
-
The `DECLARE` statement initializes a Transact-SQL variable by:
38
+
Use the `DECLARE` statement to initialize a Transact-SQL variable by:
37
39
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.
39
41
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.
41
43
42
44
- Setting the value to `NULL`.
43
45
44
46
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`.
45
47
46
48
```sql
47
-
DECLARE @MyCounter INT;
49
+
DECLARE @MyCounter ASINT;
48
50
```
49
51
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.
51
53
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`:
In another example, the following `DECLARE` statement creates a Boolean variable called `@IsActive`, which is declared as **bit** with a value of `0` (`false`):
59
63
60
64
```sql
61
-
DECLARE @IsActive BIT=0;
65
+
DECLARE @IsActive ASBIT=0;
62
66
```
63
67
64
68
## Variable scope
65
69
66
70
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:
67
71
68
72
```sql
69
-
USE AdventureWorks2022;
73
+
USE AdventureWorks2025;
70
74
GO
71
75
72
-
DECLARE @MyVariable INT;
73
-
76
+
DECLARE @MyVariable ASINT;
74
77
SET @MyVariable =1;
75
-
GO
76
78
77
79
SELECT BusinessEntityID,
78
-
NationalIDNumber,
79
-
JobTitle
80
+
NationalIDNumber,
81
+
JobTitle
80
82
FROMHumanResources.Employee
81
83
WHERE BusinessEntityID = @MyVariable;
82
84
```
83
85
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.
85
87
86
88
```sql
87
-
DECLARE @MyVariable INT;
89
+
DECLARE @MyVariable ASINT;
88
90
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".
90
100
```
91
101
92
102
## Set a value in a Transact-SQL variable
93
103
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.
95
105
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:
97
107
98
108
```sql
99
-
USE AdventureWorks2022;
109
+
USE AdventureWorks2025;
100
110
GO
101
111
102
112
-- Declare two variables.
103
-
DECLARE @FirstNameVariable NVARCHAR(50),
104
-
@PostalCodeVariable NVARCHAR(15);
113
+
DECLARE @FirstNameVariable ASNVARCHAR(50),
114
+
@PostalCodeVariable ASNVARCHAR(15);
105
115
106
116
-- Set their values.
107
117
SET @FirstNameVariable = N'Amy';
108
118
SET @PostalCodeVariable = N'BA5 3HX';
109
119
110
120
-- Use them in the WHERE clause of a SELECT statement.
111
121
SELECT LastName,
112
-
FirstName,
113
-
JobTitle,
114
-
City,
115
-
StateProvinceName,
116
-
CountryRegionName
122
+
FirstName,
123
+
JobTitle,
124
+
City,
125
+
PostalCode,
126
+
StateProvinceName,
127
+
CountryRegionName
117
128
FROMHumanResources.vEmployee
118
129
WHERE FirstName = @FirstNameVariable
119
-
OR PostalCode = @PostalCodeVariable;
120
-
GO
130
+
OR PostalCode = @PostalCodeVariable;
121
131
```
122
132
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:
124
134
125
135
```sql
126
-
USE AdventureWorks2022;
136
+
USE AdventureWorks2025;
127
137
GO
128
-
DECLARE @EmpIDVariable INT;
129
138
130
-
SELECT @EmpIDVariable =MAX(EmployeeID)
139
+
DECLARE @EmpIDVariable ASINT;
140
+
141
+
SELECT @EmpIDVariable =MAX(BusinessEntityID)
131
142
FROMHumanResources.Employee;
132
-
GO
133
143
```
134
144
135
145
> [!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.
137
147
138
148
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`:
139
149
140
150
```sql
141
-
USE AdventureWorks2022;
151
+
USE AdventureWorks2025;
142
152
GO
143
-
DECLARE @EmpIDVariable INT;
153
+
154
+
DECLARE @EmpIDVariable ASINT;
144
155
145
156
SELECT @EmpIDVariable = BusinessEntityID
146
157
FROMHumanResources.Employee
147
158
ORDER BY BusinessEntityID DESC;
148
159
149
160
SELECT @EmpIDVariable;
150
-
GO
151
161
```
152
162
153
163
## Examples
@@ -156,54 +166,50 @@ The following script creates a small test table and populates it with 26 rows. T
156
166
157
167
- Control how many rows are inserted by controlling how many times the loop is executed.
158
168
- 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.
160
170
161
171
```sql
162
172
-- Create the table.
163
-
CREATETABLETestTable (cola INT, colb CHAR(3));
164
-
GO
173
+
CREATETABLETestTable
174
+
(
175
+
cola INT,
176
+
colb CHAR (3)
177
+
);
165
178
166
179
SET NOCOUNT ON;
167
-
GO
168
180
169
181
-- Declare the variable to be used.
170
-
DECLARE @MyCounter INT;
182
+
DECLARE @MyCounter ASINT;
171
183
172
184
-- Initialize the variable.
173
185
SET @MyCounter =0;
174
186
175
187
-- Test the variable to see if the loop is finished.
176
188
WHILE (@MyCounter <26)
177
-
BEGIN;
178
189
-- Insert a row into the table.
179
-
INSERT INTO TestTable
180
-
VALUES
190
+
BEGIN
191
+
INSERT INTO TestTable
181
192
-- Use the variable to provide the integer value
182
193
-- for cola. Also use it to generate a unique letter
183
194
-- for each row. Use the ASCII function to get the
184
195
-- integer value of 'a'. Add @MyCounter. Use CHAR to
185
196
-- convert the sum back to the character @MyCounter
0 commit comments