Link to home
Start Free TrialLog in
Avatar of thewayne73
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
ASKER CERTIFIED SOLUTION
Avatar of TimCottee
TimCottee
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thewayne73,

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

DECLARE @Query NVARCHAR(2000)
DECLARE @table_name VARCHAR(50)
SET @table_name = 'mytable'
 
SET @Query = 'SELECT  * FROM ' + @table_name
 
EXECUTE sp_executesql @Query

Open in new window

Avatar of thewayne73
thewayne73

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