我在表格中有一列,我想将内容分成不同的列,短划线的位置并不总是相同。请告知更简单的代码。
感谢。
COL1
AGH-WH6X-23-4534-OPDQE-QADF
xxx-xxxx-xxxx-xxxx-xxx-xxxx
xxx-xxxx-xxxxxx-xxxx-xxxxx-xx
x-xx-xxxx-xxxxxx-xxxx-xxx-xx
xxx-xx-xxxx-xxxx-xxx-xxx-x
xxx-xxxx-xxxxxx-xxxxxx-xxx-xx
x-xxx-xxxx-xxxx-xxxxxx-xxx-xx
xxx-xxxxx-xxxx-xxxxxx-xxx-xx
期望:
COL2 COL3 COL4 COL5 COL6 COL7
AGH WH6X 23 4534 OPDQE QADF
xxx xxxx xxxx xxxx xxx NULL
答案 0 :(得分:2)
一种方法是具有聚合的递归CTE:
with cte as (
select col1, left(col1, charindex('-', col1 + '-') - 1) as val,
1 as level,
substring(col1, charindex('-', col1) + 1, len(col1)) as rest
from t
union all
select col1, left(rest, charindex('-', rest + '-') - 1),
level + 1,
substring(rest, charindex('-', rest + '-') + 1, len(col1))
from cte
where rest > ''
)
select max(case when level = 1 then val end) as val1,
max(case when level = 2 then val end) as val2,
max(case when level = 3 then val end) as val3,
max(case when level = 4 then val end) as val4,
max(case when level = 5 then val end) as val5,
max(case when level = 6 then val end) as val6,
max(case when level = 7 then val end) as val7
from cte
group by col1;