I am trying to create tables dynamically using the information in another table.
For example there is a table (say table1) which has information about the list of tables to be created. I would like to use this table1 to dynamically create new tables using the schema St. and including _New def in the end of the name i.e. I would like to create a table 'St.TableA_New' instead of the table name 'TableA' in table1. Here is the code I used.
declare @table1 table(idx int identity(1,1), table_name varchar(50))
insert into @table1 (table_name)
select'TableA' union
select'TableB' union
select'TableC'
DECLARE @COUNT INT = 1;
WHILE @COUNT <= (select count(*) from @table1)
BEGIN
Declare @table_name varchar(200) = (select table_name from @table1 where idx=@COUNT);
Declare @new_table varchar(50) = 'St.+'@table_name+'_New';
IF OBJECT_ID(@new_table) IS NOT NULL
DROP TABLE @new_table;
CREATE TABLE @new_table
WITH
(
DISTRIBUTION = ROUND_ROBIN,
HEAP
)
AS
SELECT *
FROM [Ext].[@table_name]
OPTION (LABEL = '');
SET @COUNT = @COUNT + 1
END;
The error says 'incorrect syntax near '@newtable.' Expecting '.',ID,IF,or QUOTED_ID' at the 'DROP TABLE @new_table;' line. What should I do to create all the tables dynamically using the names from 'table1' table?