简体   繁体   中英

how to create a table structure from column values of another table in MSSQL

I have a scenario where i have the entries in a column of a table with CSV ( these are dynamic values). I need to generate the tables with those values in sqlserver(MSSQL)

Input Table

Value   
FirstName,LastName,SSN  
Address1,City,Zip
HomePhone,CellPhone

Output Table1

FirstName   LastName    SSN

Output Table2

Address1    City    Zip

Output Table3

HomePhone   CellPhone

Can some one please help me.

You need dynamic SQL for this, such as:

declare @sql nvarchar(max);

with t as (
    select 'FirstName,LastName,SSN' as value union all
    select 'Address1,City,Zip' union all
    select 'HomePhone,CellPhone'
   )
select @sql = (select 'create table'+CAST(seqnum as varchar(255))+' ('+REPLACE(value, ',', ' varchar(255),') + ' varchar(255)); '
               from (select t.*, ROW_NUMBER() over (order by (select null)) as seqnum
                     from t
                    ) t
               for xml path ('')
              )

exec sp_executesql @sql;

尝试这个,

  1. Select FirstName,LastName,SSN into Table1 from #InputTable
  2. Select Address1,City,Zip into Table2 from #InputTable
  3. Select HomePhone,CellPhone into Table1 from #InputTable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM