Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 retrieve table name
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Posting Yak Master

110 Posts

Posted - 09/30/2012 :  10:17:35  Show Profile  Reply with Quote
Is it possible that I set the table name from which I want to select as a variable?
DECLARE @table varchar(800)
SELECT Column1, Column3, Column5 FROM @table

I would like to always select the table based on the month value.

Any help is appreciated.

Flowing Fount of Yak Knowledge

5155 Posts

Posted - 09/30/2012 :  18:31:21  Show Profile  Reply with Quote
SQL Server does not allow that syntax. You would have to use dynamic SQL (which would come with the baggage of SQL injection risk).

If you are still in the design stages and if you have a say in the design, instead of creating table names with the month as part of the table name, create a single table with another column that has the datestamp. That would make querying and managing the data much much easier.
Go to Top of Page

Mike Jackson
Starting Member

37 Posts

Posted - 10/01/2012 :  08:46:35  Show Profile  Reply with Quote
DECLARE @table varchar(800)
DECLARE @sql varchar(800)


set @sql = 'SELECT Column1, Column3, Column5 FROM ' + @table
print @sql

execute (@sql)

dynamic SQL often does have an SQL injection risk but this particular code would not be exposed to the user so it should be safe.


Go to Top of Page

Very Important crosS Applying yaK Herder

52326 Posts

Posted - 10/01/2012 :  10:42:37  Show Profile  Reply with Quote
do you mean you maintain a different table for each month for same data format? I would have opted to keep them in same table with an additional column(date or month) to designate month value. In case the table is huge, You can always make use partitioning to partition table based on date and put partitions onto different file groups

SQL Server MVP

Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.03 seconds. Powered By: Snitz Forums 2000