SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

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

HenryFulmer
Posting Yak Master

USA
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)
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
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 @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

India
52317 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
http://visakhm.blogspot.com/

Go to Top of Page
  Previous Topic Topic Next Topic  
 New 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.08 seconds. Powered By: Snitz Forums 2000