Solved

Pass var to table name

Posted on 2013-01-10
3
309 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 22

Accepted Solution

by:
Steve Wales earned 400 total points
ID: 38765000
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
ID: 38765237
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
ID: 38784496
Thanks!
0

Featured Post

Backup Solution for AWS

Read about how CloudBerry Backup fully integrates your backups with Amazon S3 and Amazon Glacier to provide military-grade encryption and dramatically cut storage costs on any platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If you have heard of RFC822 date formats, they can be quite a challenge in SQL Server. RFC822 is an Internet standard format for email message headers, including all dates within those headers. The RFC822 protocols are available in detail at:   ht…
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…
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

726 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