SQL add a variable to a query
<p>How do I create variables that are specified once and then used in queries later in a script? These variables may be used multiple times in a query, and in multiple queries in a script. I use <code>@x</code> as such a variable in the examples below.</p>

<p>What I want to do is something like:</p>

<pre><code>Declare @Query nvarchar(1000)
Declare @x nvarchar(40)

Set @x = 'test'
Set @Query = 'Select [Name]
                     , ' + @x + ' as [TestCase]
              From mytable'

Exec (@Query)

-- returns "Invalid column name 'test'"
</code></pre>

<p>Which returns the error mentioned above. I would like it to achieve the equivalent of:</p>

<pre><code>Declare @Query nvarchar(1000)
Declare @x nvarchar(40)

Set @x = 'test'
Set @Query = 'Select [Name]
                     , ''test'' as [TestCase]
              From mytable'

Exec (@Query)

-- Returns e.g.
-- Name   TestCase
-- Alice  Test
-- Bob    Test
</code></pre>

<p>I also note that the following doesn't work and returns the same error as the first:</p>

<pre><code>Declare @Query nvarchar(1000)
Declare @x nvarchar(40)

Set @x = 'test'
Set @Query = 'Select [Name]
                     , ' + 'test' + ' as [TestCase]
              From mytable'

Exec (@Query)

-- returns "Invalid column name 'test'"
</code></pre>

<p>Based on the error and since I'm not trying to use the <code>@x</code> as a column name, but just as a variable, I assume I'm using an invalid implementation of a variable.</p>