最近可以閒一下發個SQL小測試~看大家如何寫SQL
基本上這題有很多SQL寫法啦
提供基本資料
declare @Str varchar(max) = '-22,55,66,11,-44'
轉換如圖
在還沒有支援STRING_SPLIT版本之前,可以用這方式將逗號轉成多行
declare @Str varchar(max) = '-22,55,66,11,-44'
declare @x xml = '<row>' + REPLACE(@Str, ',','</row><row>')+ '</row>'
select ROW_NUMBER() over(order by (select 1)) as Sort
,item.c.value('.', 'int') AS list
from @x.nodes('*') item (c)
--或者
declare @Str varchar(max) = '-22,55,66,11,-44'
select ROW_NUMBER() over(order by (select 1)) as Sort
,list
from (
select CONVERT(XML, '<n>' + replace(@Str, ',', '</n><n>') + '</n>') Str
) k
outer apply (
select item.c.value('.', 'int') AS list
from k.Str.nodes('*') item (c)
) s
--或者
declare @Tmp table(
Str nvarchar(max)
)
insert into @Tmp
values('-22,55,66,11,-44')
select ROW_NUMBER() over(order by (select 1)) as Sort
,list
from (
select CONVERT(XML, '<n>' + replace(Str, ',', '</n><n>') + '</n>') Str
from @Tmp
) k
outer apply (
select item.c.value('.', 'int') AS list
from k.Str.nodes('*') item (c)
) s
MS SQL 2016 開始有 string_split() 可以使用
declare @Str varchar(max) = '-22,55,66,11,-44'
SELECT * from string_split(@Str , ',' , 1)
建立資料
select *
into #temp
from (
values
(1, '-22,55,66,11,-44'),
(2, 'A,B,C,D,E,F'),
(3, 'G,H,I,J')
) as T(id, s)
從table拆出來
select *
from #temp T
CROSS APPLY string_split(T.s, ',')
再把它組回去
WITH temp as (
select *
from #temp T
CROSS APPLY string_split(T.s, ',')
)
select T1.id,
stuff(
(
select ',' + T2.[value]
from temp T2 where t1.id = t2.id for xml path('')
), 1, 1, ''
)
from temp T1
group by t1.id