Why does declare @x int = 1, @y int = @x; not work in SQL Server?

Question:

This code:

declare @x int = 1, @y int = @x;

gives the error:

Must declare the scalar variable "@x".

I read through the Microsoft documentation for the DECLARE keyword along with some other sources, but none thoroughly explained this behavior. There is only a part specifying:

multiple variables can be specified and assigned values.

My reasoning is that, similar to evaluating expressions in a SELECT statement, all declarations occur simultaneously with no guarantee of order. Or, as SQL server parses the line, it doesn't run the DECLARE command until it reaches the end of the line. When @y int = @x is reached, @x does not exist because the DECLARE command for @x hasn't run yet.

What is the correct answer?

Answer:

You're on the right track. The error you're encountering occurs because of how SQL Server parses and binds variable declarations — specifically, how it handles initializations within a single DECLARE statement. In SQL Server, you cannot reference a variable declared earlier in the same DECLARE statement when initializing another variable. All variables in the DECLARE block are treated as being declared simultaneously, so their initial values cannot depend on each other.

declare @x int = 1, @y int = @x;

Here:

  • @x is declared and initialized with the value 1.
  • @y is declared and initialized with the value of @x.

However, SQL Server parses the entire declaration as a single unit.

When it reaches @y int = @x, @x is not yet in scope — because none of the variables in the statement are available until the entire DECLARE finishes parsing.

As a result, you'll get this error:

Must declare the scalar variable "@x".

Solution - Use separate DECLARE statements — one for each variable:

declare @x int = 1;
declare @y int = @x;

Рисунок

Now @x exists when @y is initialized, so this works correctly.

SQL development tools like dbForge for SQL Server can help detect such scope-related issues early with syntax checking and smart code suggestions — useful when working with complex scripts.

0
Subscribe to my newsletter

Read articles from Gabriella Barajas directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Gabriella Barajas
Gabriella Barajas

A database Q&A blog for those who’d rather debug queries than read documentation. Practical answers to real questions — mostly SQL Server and MySQL, with a pinch of sarcasm and a love for clean code.