I got so far on coding and got to read one table and then recreate this table as another name.
The end result is the table is identical to the one i am copying but i am adding a column of EXTRACT_ID to the table.
There will be over 20 tables so i wanted to recreate them all dynamically.
I am not sure how to put the code for the varchar NOT NULL, aswell.
Declare @StartTable sysname,
@ExtractTable sysname,
@TargetExtractTable sysname,
@sourceTable sysname, @DBSource sysname,
@SQLInsertString NVARCHAR(max),
@SQLCreateExtractTable NVARCHAR(max),
@TrackerTablePrimaryColumn NVARCHAR(MAX),
@SQLLine1 NVARCHAR(max),
@SQLLine1A NVARCHAR(max),
@SQLLine2 NVARCHAR(max),
@SQLLine3 NVARCHAR(max),
@SQLLine4 NVARCHAR(max),
@SQLLine5 NVARCHAR(max),
@SQLLine6 NVARCHAR(max),
@SQLLine7 NVARCHAR(max),
@SQLLine8 NVARCHAR(max),
@SQLLine5A NVARCHAR(max),
@SQLLine5B NVARCHAR(max),
@columnnames as varchar(max),
@StartTableName sysname
Select @StartTable='DBO.EMPLOYEES' , ----This can be any table i just want to mirror it.
@columnnames='['
Select @StartTableName = 'EMPLOYEES'
select @ExtractTable = 'NEW_EMPLOYEES'
select @DBSource = 'NEW_SOURCE'
select @SourceTable = 'DBO.EMPLOYEES'
Select @columnnames=@columnnames+sc.name+'],['
from sys.all_columns sc
where sc.object_id=object_ID(@SourceTable)
ORDER BY column_id
select @columnnames=left(@columnnames,len(@columnnames)-2) --get rid of the open bracket at the end
---Only Add table if not exist recreate table
select @SQLLine1A = 'if not exists (select * from sysobjects where name=' + @ExtractTable + ' ' + ' AND ' + 'xtype=' + 'U' + ')'
Print @SQLLine1A
select @SQLCreateExtractTable = 'CREATE TABLE ' + @ExtractTable + '(' + '[EXTRACT_KEY_ID]' + ',' + @columnnames + ')' + CHAR(13) + 'GO' + CHAR(13)