SQL将逗号分隔列转换为行并将其保存到另一个表中

时间:2015-05-23 18:10:57

标签: sql sql-server sql-server-2008

我有一个名为food的表,其中包含speciality列。行上的值:

Speciality (column name)
......................................

Chinese, south Indian, Mediterranean, American
......................................

South Indian, fast food, shakes, coldrinks, Chinese

......................................

我想在不同的行上作为唯一值,例如:

South Indian
Chinese
Mediterranean
American
Fast food
Shakes

并将其保存到列名为food2的另一个表speciality2,我想将这些值保存到该列中。

SQL Server 2008中的所有数据库。

1 个答案:

答案 0 :(得分:0)

我认为split函数和XML可以帮助你 尝试以下代码

Insert Into Food2(Speciality2)
SELECT   Distinct
     Split.a.value('.', 'VARCHAR(100)') AS String  
 FROM  (SELECT  
         CAST ('<M>' + REPLACE([Speciality], ',', '</M><M>') + '</M>' AS XML) 
     AS String  
     FROM  food) AS A CROSS APPLY String.nodes ('/M') AS Split(a);