Solved

Pass var to table name

Posted on 2013-01-10
3
305 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
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

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Question has a verified solution.

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

Suggested Solutions

Naughty Me. While I was changing the database name from DB1 to DB_PROD1 (yep it's not real database name ^v^), I changed the database name and notified my application fellows that I did it. They turn on the application, and everything is working. A …
Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, just open a new email message. In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…

864 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

25 Experts available now in Live!

Get 1:1 Help Now