首页 > 解决方案 > 将逗号分隔的值拆分为多列

问题描述

我有一个要求,我的 SQL 表中有这样格式的列:

SQL 列

如何使用逗号分隔符拆分数据并将其插入同一张表中新添加的列中?

在此处输入图像描述

标签: sqlsql-serverssis

解决方案


您的样本数据可能不需要任何拆分。您希望根据找到的值将数据移动到列中。您可以比拆分数据更简单一些。这适用于您的示例数据。

declare @Something table
(
    Combined_Column varchar(10)
)

insert @Something values
('1,2,3')
, ('2')
, ('1,3')
, ('1,2,3,4')
, ('1,3,4')
, ('1')
, ('4')

select *
    , col1 = case when charindex('1', s.Combined_Column) > 0 then 1 end
    , col2 = case when charindex('2', s.Combined_Column) > 0 then 2 end
    , col3 = case when charindex('3', s.Combined_Column) > 0 then 3 end
    , col4 = case when charindex('4', s.Combined_Column) > 0 then 4 end
from @Something s

推荐阅读