带分隔符的SQL子查询
我需要能够通过分隔符*将一个字符串拆分为单独的列,而不包括* 表x中的y列如下所示:带分隔符的SQL子查询,sql,sql-server,Sql,Sql Server,我需要能够通过分隔符*将一个字符串拆分为单独的列,而不包括* 表x中的y列如下所示: column y *1HS*AB*GXX*123*02*PA45*2013-08-10* *1R1*B*GX*123*02*PA45*2013-08-10* *1HS*B*GX*13*01*PA45*2013-08-01* *1P*C*GXX*123*02*PA45*2013-08-10* 字符串分割不可用 结果应该是: Column1 Column2 Column3 Column4 Column5 Colu
column y
*1HS*AB*GXX*123*02*PA45*2013-08-10*
*1R1*B*GX*123*02*PA45*2013-08-10*
*1HS*B*GX*13*01*PA45*2013-08-01*
*1P*C*GXX*123*02*PA45*2013-08-10*
字符串分割不可用
结果应该是:
Column1 Column2 Column3 Column4 Column5 Column6 Column7
1HS AB GXX 123 2 PA45 10-08-2013
1R1 B GX 123 2 PA45 10-08-2013
1HS B GX 13 1 PA45 01-08-2013
1P C GXX 123 2 PA45 10-08-2013
不幸的是,string_split不能保证它保留值的顺序。而且,SQLServer不提供其他有用的字符串函数
因此,我建议为此使用递归CTE:
with t as (
select *
from (values ('*1HS*AB*GXX*123*02*PA45*2013-08-10*'), ('1HSB*GX*13*01*PA45*2013-08-01*')) v(str)
),
cte as (
select convert(varchar(max), null) as val, 0 as lev, convert(varchar(max), str) as rest,
row_number() over (order by (select null)) as id
from t
union all
select left(rest, charindex('*', rest) - 1), lev + 1, stuff(rest, 1, charindex('*', rest) + 1, ''), id
from cte
where rest <> '' and lev < 10
)
select max(case when lev = 1 then val end) as col1,
max(case when lev = 2 then val end) as col2,
max(case when lev = 3 then val end) as col3,
max(case when lev = 4 then val end) as col4,
max(case when lev = 5 then val end) as col5,
max(case when lev = 6 then val end) as col6,
max(case when lev = 7 then val end) as col7
from cte
where lev > 0
group by cte.id;
是一个dbfiddle。您会使用下面的查询吗
select RTRIM (REGEXP_SUBSTR (column y, '[^,]*,', 1, 1), ',') AS column 1
, RTRIM (REGEXP_SUBSTR (column y, '[^,]*,', 1, 2), ',') AS column 2
, RTRIM (REGEXP_SUBSTR (column y, '[^,]*,', 1, 3), ',') AS column 3
, LTRIM (REGEXP_SUBSTR (column y, ',[^,]*', 1, 3), ',') AS column 4
from YOUR_TABLE
假设您可以向数据库中添加表值函数,那么Jeff Moden的字符串拆分函数是我遇到的最好的方法。它也能让你维持秩序
REGEXP_SUBSTR不是T-SQLfunction@GordonLinoff为什么你会建议这不是;它的一个副本似乎是一个完全相同的副本。OP希望将分隔列表转换为列。