Solved

Pass var to table name

Posted on 2013-01-10
3
304 Views
Last Modified: 2013-01-16
Is it possible to pass a var into the table name? i.e.:

/**************************/
declare @monthEnd varchar(8) = '12312012'

select
   *
into
   tableName_@monthEnd
/**************************/

So "tableName_12312012" is the actual table name.

Thanks!
0
Comment
Question by:Rickzzz
3 Comments
 
LVL 22

Accepted Solution

by:
Steve Wales earned 400 total points
Comment Utility
You could do it with dynamic sql

declare @monthend varchar(8)
declare @sql nvarchar(4000)

set @monthend = '12312012'

set @sql = 'select * into tableName_'+@monthEnd+' from whereever'
exec (@sql)

Open in new window


Talked to Mr Google and found an example: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=68177 - with a link to a very long blog post on dynamic SQL.
0
 
LVL 26

Assisted Solution

by:Chris Luttrell
Chris Luttrell earned 100 total points
Comment Utility
The only way to do it is with dynamic sql. You can not substitue what would be SYSNAMEs, i.e. Tables, Columns, Schemas, with variables.  You have to build the SQL statement as a string and execute it with exec(@sql) or the prefered system procedure EXECUTE_SQL @sql, see Kimberly L. Tripp's article on Execute_SQL
0
 

Author Closing Comment

by:Rickzzz
Comment Utility
Thanks!
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now