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 @x as such a variable in the examples below.
What I want to do is something like:
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'"
Which returns the error mentioned above. I would like it to achieve the equivalent of:
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
I also note that the following doesn't work and returns the same error as the first:
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'"
Based on the error and since I'm not trying to use the @x as a column name, but just as a variable, I assume I'm using an invalid implementation of a variable.