Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Pass var to table name

Posted on 2013-01-10
3
Medium Priority
?
320 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 23

Accepted Solution

by:
Steve Wales earned 1600 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 27

Assisted Solution

by:Chris Luttrell
Chris Luttrell earned 400 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

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

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

Long way back, we had to take help from third party tools in order to encrypt and decrypt data.  Gradually Microsoft understood the need for this feature and started to implement it by building functionality into SQL Server. Finally, with SQL 2008, …
This is basically a blog post I wrote recently. I've found that SARGability is poorly understood, and since many people don't read blogs, I figured I'd post it here as an article. SARGable is an adjective in SQL that means that an item can be fou…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Screencast - Getting to Know the Pipeline

810 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