The "Error 137: Must declare the scalar variable" in SQL Server occurs when the query expects a variable to be defined but finds none—either because the variable is missing a declaration, referenced before assignment, or the wrong syntax is used. This typically happens in dynamic SQL, stored procedures, or table-valued functions. The fix involves properly declaring and initializing variables before use and ensuring the variable name matches exactly in both declaration and usage.
What You'll Need
- A working SQL Server instance (2008 and later)
- Access to SSMS (SQL Server Management Studio) or a T-SQL editor
- Basic knowledge of T-SQL syntax (tables, joins, variables)
- A test database or sample data to work with
- Admin privileges to run procedures or scripts that might be failing
Step-by-Step
-
Identify the problematic variable reference:
Open the query that generates Error 137. Look for a reference to a variable that is either:
- Used without a preceding
DECLAREstatement - Called before
SET @var = value - Assigned a value in one context but referenced in another (e.g., string concatenation vs. numeric arithmetic)
SELECT * FROM Orders WHERE SalesPerson = @SalesPerson_ID; -- Error if @SalesPerson_ID is undeclared - Used without a preceding
-
Declare and initialize variables correctly:
Add a
DECLAREstatement before the query and initialize it:DECLARE @SalesPerson_ID INT = 100; SELECT * FROM Orders WHERE SalesPerson = @SalesPerson_ID;For scalar variables (single values), use:DECLARE @var_name data_type = default_value;For table-valued variables, use:DECLARE @table_var table_column_name data_type; -
Fix scope mismatches:
If the same variable is used in multiple contexts (e.g., string concatenation vs. arithmetic), ensure type consistency:
DECLARE @customer_name NVARCHAR(100) = 'John Doe'; SELECT @customer_name + ' ordered ' + @order_count + ' items'; -- Error if @order_count is INT but concatenatedSolution:DECLARE @customer_name NVARCHAR(100) = 'John Doe'; DECLARE @order_count INT = 5; SELECT @customer_name + ' ordered ' + CAST(@order_count AS NVARCHAR(10)) + ' items'; -
Use dynamic SQL carefully:
If the error appears in dynamic SQL (e.g.,
EXEC('SELECT ...')), ensure the variable is declared in the outer scope:DECLARE @sql NVARCHAR(MAX) = 'SELECT * FROM Table1 WHERE ID = @id'; DECLARE @id INT = 123; EXEC sp_executesql @sql, N'@id INT', @id;If the variable is local to the dynamic SQL block, declare it in the procedure body before the EXEC line. -
Check variable naming conventions:
SQL Server is case-insensitive for keywords but case-sensitive for variable names. Ensure:
- The name matches exactly (e.g.,
@salesperson_idvs.@SalesPersonId). - No reserved keywords are used as variable names (e.g.,SELECT,GROUP). Example:-- Avoid this (reserved keyword) DECLARE @SELECT INT = 1; SELECT * FROM Table1;-- Correct DECLARE @search_key INT = 1; SELECT * FROM Table1; -
Test in a minimal environment:
Create a standalone query to isolate the issue. Example:
BEGIN TRY DECLARE @test_var INT; SELECT * FROM Users WHERE UserID = @test_var; -- Error if @test_var is undeclared END TRY BEGIN CATCH PRINT 'Error: Must declare the scalar variable';If this fails, the issue is confirmed. If it works, the problem is in the full query's scope. -
Review stored procedures:
If the error occurs in a stored procedure, check:
- The procedure signature (e.g.,
CREATE PROCEDURE GetOrders(@customer_id INT)). - Variable declarations inside the procedure (e.g.,DECLARE @temp_result INT;). - Dynamic SQL calls within the procedure.
Common Mistakes
- Omitting the
DECLAREstatement: Forgetting to declare a variable before using it, especially in dynamic SQL or multi-line queries. - Using variables before assignment: Referencing a variable like
@var = @valuewithout first declaring it. - Mismatched variable types: Assigning a value of one type (e.g., string) to a variable declared as another type (e.g., integer), or vice versa. Example:
DECLARE @price DECIMAL(10,2); -- Expects decimal SET @price = '100'; -- Error: Cannot convert string to numericSolution: Cast the value to the correct type (e.g.,CAST(@price AS DECIMAL)). - Scope leaks: Declaring a variable in one context (e.g., a stored procedure) and using it in a block where it’s not accessible.
- Typos in variable names: A single character difference (e.g.,
@salesPersonvs.@SalesPerson) can cause the query to fail. - Assuming variables are global: Variables scoped to a procedure or block may not be available in other contexts unless explicitly passed.
Tips
- Use SQL Server Profiler or Extended Events to trace variable references and identify undeclared usages.
- Enable query hints (e.g.,
WITH (NOLOCK)) to test if the issue is isolated to specific query paths. - Leverage SQL Server’s intellisense in SSMS to catch variable name typos early.
- Check for implicit conversions: SQL Server may silently convert types in some contexts (e.g.,
INTtoNVARCHAR), but this can hide errors. Always explicit the type. - Use parameterized queries for dynamic SQL to avoid variable scope issues:
DECLARE @sql NVARCHAR(MAX) = 'SELECT * FROM Orders WHERE OrderID = @order_id'; EXEC sp_executesql @sql, N'@order_id INT', @order_id = 123;
Troubleshooting
If the error persists after the above steps:
-
Restart the SQL Server service to clear any temporary state:
net stop MSSQLSERVER; net start MSSQLSERVER;(Windows) or restart the service via Services.msc (Linux/macOS:sudo systemctl restart postgresql). This sometimes resolves cached variable definitions or connection issues. - Recreate the query in a new session to rule out scope or state-related errors. Open a fresh SSMS instance and run the problematic query again.
-
Check for conflicting variable names in the database. Run:
SELECT name, type_name FROM sys.objects WHERE type = 'V'; -- Lists all user variablesEnsure no other variable shadows your intended variable (e.g.,@@ROWCOUNTis a system variable). -
Update SSMS or SQL Server to the latest patch level, as some bugs are fixed in updates:
- For SSMS:
Settings > Options > Results To Grid > T-SQL Errors and Warningsto ensure detailed error messages. - For SQL Server: Download the latest cumulative update from Microsoft.
- For SSMS:
-
Inspect the exact error message for additional context. Look for:
- Line numbers pointing to the issue
- Suggestion messages (e.g., "Declare the scalar variable @var")
- Type mismatches or scope errors
Msg 213, Level 16, State 1, Line 5 Must declare the scalar variable "@salesperson_id". Msg 207, Level 16, State 1, Line 5 Conversion failed when converting the varchar value 'John Doe' to data type int.The first error indicates the undeclared variable; the second shows a type mismatch. -
Review the database’s isolation level if the query involves transactions. Switch to
READ COMMITTEDorSNAPSHOTisolation to avoid unintended blocking:SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
Frequently Asked Questions
Why does SQL Server complain about declaring a scalar variable if it’s already declared elsewhere in the script?
The error occurs if the variable is declared in a different scope (e.g., a procedure) or if the query uses a parameterized approach where the variable name is dynamically generated. Always ensure the variable is declared in the immediate scope of the query that references it.
How can I debug a variable scope issue without rewriting the entire query?
Use a temporary variable to shadow the problematic one:
DECLARE @temp_var INT;
SET @temp_var = @var; -- Replace @var with the actual variable
-- Now use @temp_var instead where the error occurs
Replace the references in the query with @temp_var and test. If it works, revert the changes.
Is there a way to avoid declaring every variable in a complex stored procedure?
Yes, use parameters or table-valued inputs for reusable logic:
CREATE PROCEDURE GetOrdersByCustomer(
@customer_id INT,
@min_amount DECIMAL(10,2)
) AS
BEGIN
DECLARE @sql NVARCHAR(MAX) = 'SELECT * FROM Orders WHERE CustomerID = @customer_id AND Amount >= @min_amount';
EXEC sp_executesql @sql, N'@customer_id INT, @min_amount DECIMAL(10,2)', @customer_id, @min_amount;
END;
Parameters are implicitly declared and passed to the procedure.
Can I use a variable declared in one query in another query in the same session?
No. Variables are session-scoped by default. If you need shared state, use:
- Application variables (set via
SET @var = valuein a session script), - Tables or temp tables (e.g.,
SELECT * FROM #TempTable), or - Stored procedures with parameters or output parameters.
-- Session 1
SET @shared_var = 'Hello';
-- Session 2
SELECT @@APPVAR; -- Returns 'Hello' if session 1 set it.
(Note: Application variables are session-specific and may not persist across sessions.)
Why does the error appear in a CTE (Common Table Expression) but not in the outer query?
The error typically stems from a variable referenced in the CTE’s subquery but not declared in the CTE itself. Ensure:
WITH CTE AS (
SELECT @var = 100 -- Error if @var is undeclared
FROM Table1
)
SELECT * FROM CTE;
Move the variable declaration into the CTE or declare it at the top of the query. CTEs are evaluated as part of the outer query’s scope.
How do I handle variables in a FOR XML PATH query?
In FOR XML PATH, variables are evaluated during query execution. If the variable is undeclared, the error occurs because the query cannot resolve the reference. Example:
DECLARE @path NVARCHAR(100) = 'Parent/Child';
SELECT @path AS Path -- Error if @path is undeclared
FROM Table1 FOR XML PATH('Data');
Solution: Declare the variable before the query:
DECLARE @path NVARCHAR(100) = 'Parent/Child';
SELECT @path AS Path FROM Table1 FOR XML PATH('Data');
For dynamic XML paths, use sp_executesql with parameters as shown earlier.