thewayne73
asked on
Using variable for table name
hello experts,
how can i use a variable for the table name?
declare @table_name varchar(2000)
set @table_name = 'mytable'
select *
from @table_name
I would have thought it was that easy, but it wants me to declare the table variable. i read up on table variables, and that talks about storing values...not wanting to do that.
thanks
how can i use a variable for the table name?
declare @table_name varchar(2000)
set @table_name = 'mytable'
select *
from @table_name
I would have thought it was that easy, but it wants me to declare the table variable. i read up on table variables, and that talks about storing values...not wanting to do that.
thanks
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
DECLARE @Query NVARCHAR(2000)
DECLARE @table_name VARCHAR(50)
SET @table_name = 'mytable'
SET @Query = 'SELECT * FROM ' + @table_name
EXECUTE sp_executesql @Query
ASKER
Thanks...i was creating dynamic sql..but that can end up looking nasty. using this solution will work for most of what i am dong.
wayne
wayne
You have to use Dynamic sql, in otherwords build your required statement as a string and then use exec() to actually execute the statement. Sql Server does not do direct macro replacement in the way you were thinking.
TimCottee