Hi all,I hope the following makes sense. Please feel free to ask me any questions about my problem!The objective of this exercise is pretty straightfoward. I want to be able to create a new table dynamically. I have the following table which contains my column headers for the new tablecreate table dbo.MyTypeLessTable ( Ident int identity(1, 1), ColumnNames varchar(200))insert into dbo.MyTypeLessTable (ColumnNames)select 'Column1' unionselect 'DD_Addr1' union select 'DD_Addr2' unionselect 'DD_Addr3' unionselect 'DD_County' unionselect 'Column6' unionselect 'Column7' unionselect 'Column8'
Seems simple enough, the follownig code will generate the sql string for my new table :declare @ColumnHolder varchar(200)declare @sql varchar(max)declare @Ident tinyintset @Ident = 1set @sql = 'create table Staging.dbo.myResult ('set @ColumnHolder = (select ColumnNames from dbo.MyTypeLessTable where Ident = @Ident)while @ColumnHolder is not null begin set @sql = @sql + '[' + @ColumnHolder + '] varchar(200),' set @Ident = @Ident + 1 set @ColumnHolder = (select ColumnNames from MyTypeLessTable where Ident = @Ident) endset @sql = left(@sql, len(@sql)-1)+')'select @sqlMy problem is the columns prefixed with DD_ For these ones I want to set their data type and length to be the same as column in another table.The table that has the same named columns is :create table dbo.MyTypedTable ( DD_Addr1 varchar(50), DD_Addr2 varchar(90), DD_Addr3 varchar(20), DD_County varchar(100) )
I know I need to use INFORMATION_SCHEMA.COLUMNS but for the lifeof me, i can't figire out how to include this bit of logicin to my above WHILE loop.The sql string that should be generated at the end should be : create table Staging.dbo.myResult ([Column1] varchar(200),[Column6] varchar(200),[Column7] varchar(200),[Column8] varchar(200),[DD_Addr1] varchar(50),[DD_Addr2] varchar(90),[DD_Addr3] varchar(20),[DD_County] varchar(100))Your help would be much appreciated!