select * into @local_var_name from (select subquery)

m trying to create a table dynamically.

I hav local var @local_var varchar(20)

set @local_var ='some_text'

now i want to dynamically create a table wit the same value stored in @local_var

I am doing Select * into @local_var from (select subquery) Alias

but I am unable to resolve the part in bold. I have been trying with different combinations of single quotes and double quotes but sometimes it tool @local_Var as table name instead of text value stored in that variable.. 

Thanks in advance.

August 20th, 2013 10:15am

Hi ashay_88,

With the following codes,  @local_var will be took as a variable rather than a table name.

Select * into @local_var from (select subquery) Alias

You can refer to the following codes to achieve your requirement.

declare @local_var varchar(20);
declare @sql varchar(max);
set @local_var = 'TableName';
set @sql = 'select * into '+@local_var+' from(
SELECT TOP 10 [BusinessEntityID]
      ,[Title]
      ,[FirstName]
      ,[MiddleName]
      ,[LastName]
  FROM [AdventureWorks2012].[Person].[Person]) as TableAlias';
  exec(@sql)

Free Windows Admin Tool Kit Click here and download it now
August 21st, 2013 3:24am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics