如何从分隔的字符串创建多个列

时间:2012-11-19 20:04:57

标签: sql-server sql-server-2008

我有一个包含4个组件的库存字段,每个组件用“ - ”分隔。我不确定如何使用charindex来解析字符串,以便为delmiters之间的每个值返回一列。例如:字段值或字符串= item-color-size-shape。

我的目标是最终得到一个项目作为列,颜色作为列,大小作为列,最后是形状。

2 个答案:

答案 0 :(得分:1)

如果是最多4列,您可以尝试这样:

declare @Table table (SomeColumn varchar(100));
insert into @Table
    select 'ball-blue-small-round'  union all
    select 'ball-red-small-round'   union all
    select 'ball-green-small-round' union all
    select 'ball---square'          union all
    select '----';

;with stage (s)
as  (   select  replace(SomeColumn, '-', '.')
        from    @Table
    )
select  [item] = parsename(s,4),
        [color] = parsename(s,3),
        [size] = parsename(s,2),
        [shape] = parsename(s,1)
from    stage;

如果是> 4请回复,我们可以开发更具活力的解决方案。

答案 1 :(得分:0)

使用CROSS APPLY(使用冗长的名称来理解) -

declare @Table table (SomeColumn varchar(100));
insert into @Table
select 'ball-Orange-small-round'  union all
select 'bat-blue-medium-square'   union all
select 'stumps-green-large-rectangle'

SELECT * FROM @Table

SELECT Sub1.FirstSub1 AS Item
       ,Sub2.SecondSub1 AS Color
       ,Sub3.ThirdSub1 AS Size
       ,SubAfterThirdHyphen AS Shape 

FROM @Table 
CROSS APPLY (SELECT CHARINDEX('-',SomeColumn) AS FirstHyphenPos) AS Pos1
CROSS APPLY (SELECT SUBSTRING(SomeColumn,1,FirstHyphenPos-1) AS FirstSub1) AS Sub1
CROSS APPLY (SELECT SUBSTRING(SomeColumn,FirstHyphenPos+1,LEN(SomeColumn)) AS SubAfterFirstHyphen) AS Substr1

CROSS APPLY (SELECT CHARINDEX('-',Substr1.SubAfterFirstHyphen) AS SecondHyphenPos) AS Pos2
CROSS APPLY (SELECT SUBSTRING(Substr1.SubAfterFirstHyphen,1,SecondHyphenPos-1) AS SecondSub1) AS Sub2
CROSS APPLY (SELECT SUBSTRING(Substr1.SubAfterFirstHyphen,SecondHyphenPos+1,LEN(Substr1.SubAfterFirstHyphen)) AS SubAfterSecondHyphen) AS Substr2

CROSS APPLY (SELECT CHARINDEX('-',Substr2.SubAfterSecondHyphen) AS ThirdHyphenPos) AS Pos3
CROSS APPLY (SELECT SUBSTRING(Substr2.SubAfterSecondHyphen,1,ThirdHyphenPos-1) AS ThirdSub1) AS Sub3
CROSS APPLY (SELECT SUBSTRING(Substr2.SubAfterSecondHyphen,ThirdHyphenPos+1,LEN(Substr2.SubAfterSecondHyphen)) AS SubAfterThirdHyphen) AS Substr3