views:

1457

answers:

3
declare @test varchar(20)
set @test = 'VALUE'

exec('
select '+@test+'
')

This returns:

Invalid column name 'VALUE'.

Is there an alternate method to display the variable value on the select statement?

+3  A: 

You don't need to use Exec in this context If you are doing a direct assignment you can use

Set @test = 'VALUE'

and to display the value just select it without assigning a value

Select @test
cmsjr
I want to use it inside an exec command.
Joel
+3  A: 

cmsjr has a point about not needing exec for this. But assuming you're posting a simplified version of the problem and exec is a requirement:

There's no column named "value" because there's no table. If you just want it to print value, you need to encase it in quotes so it looks like a string literal inside the call to exec:

exec(' select ''' + @test + ''' ')
Joel Coehoorn
Beware SQL Injection when writing code like this.
Robin Day
Good point. Where will the data for your @test variable come from? Even if it's a somewhat trusted source, you could be creating a 2nd order vulnerability.
Joel Coehoorn
I need to create dynamic tsql to select between 5 different sources within the same sql instance. The variables will come from date pre-calculations done in the same sp that runs the exec command prior to executing it.
Joel
if you're certain you're only using a portion of a datetime data type as your additional parameter, you should be okay. Also look into sp_executesql
Joel Coehoorn
Rather than using dynamic SQL, you might be better off using a view across all of your data sources using UNION with a hard-coded value in the view to determine the source from which the data comes.
Tom H.
+6  A: 

The clean alternative is to use sp_executesql() and its ability to deal with parameterized statements:

DECLARE @test VARCHAR(20)
DECLARE @stmt NVARCHAR(100)
DECLARE @parm NVARCHAR(100)

SET @stmt = N'SELECT @val'        /* statement definition */
SET @parm = N'@val VARCHAR(20)'   /* parameters definition */
SET @test = 'VALUE'

EXECUTE sp_executesql @stmt, @parm, @val = @test

Yields:

(no column name)
VALUE
Tomalak
How would the from statement look like if I wanted to dynamically select the database using another variable?
Joel
Your question did not seem to go into this direction for me. It either looked like a variable scoping problem or a semantics/syntax misunderstanding on your side. I covered the former option, Joel Coehoorn covered the latter.
Tomalak