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

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 retrieve table name

Author  Topic 

HenryFulmer
Posting Yak Master

110 Posts

Posted - 2012-09-30 : 10:17:35
Is it possible that I set the table name from which I want to select as a variable?
DECLARE @table varchar(800)
SET @table = RIGHT(CAST(MONTH(CURRENT_TIMESTAMP) AS VARCHAR),2)
SELECT Column1, Column3, Column5 FROM @table


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

Any help is appreciated.

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-09-30 : 18:31:21
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 - 2012-10-01 : 08:46:35
DECLARE @table varchar(800)
DECLARE @sql varchar(800)

SET @table = RIGHT(CAST(MONTH(CURRENT_TIMESTAMP) AS VARCHAR),2)

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.

Mike



Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-10-01 : 10:42:37
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
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -