简体   繁体   English

如何从MSSQL中的另一个表的列值创建表结构

[英]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). 我有一种情况,其中我在带有CSV的表的列中具有条目(这些是动态值)。 I need to generate the tables with those values in sqlserver(MSSQL) 我需要在sqlserver(MSSQL)中使用这些值生成表

Input Table 输入表

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

Output Table1 输出表1

FirstName   LastName    SSN

Output Table2 输出表2

Address1    City    Zip

Output Table3 输出表3

HomePhone   CellPhone

Can some one please help me. 有人可以帮帮我吗。

You need dynamic SQL for this, such as: 为此,您需要动态SQL,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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