如何通过替换 SQL 中的特殊字符来转换给定的字符串?
How to pivot given string by replacing special characters in SQL?
在一次采访中,有人要求我通过替换特殊字符来转换字符串。
给定的字符串是 'AAA%BBB$CCC#DDD'
预期输出如图像所示:
我们如何在 SQL 服务器中执行此操作?提前致谢!
In SQL Server 2014?(我猜你用的操作系统是Windows Server 2008 R2,哈哈哈),
如果你使用SQL Server 2014-,基本上,你需要先统一不同的分隔符,
declare @str as varchar(1024) = 'AAA%BBB$CCC#DDD'
set @str = REPLACE(@str, '%', ',')
set @str = REPLACE(@str, '$', ',')
set @str = REPLACE(@str, '#', ',')
然后像这样:
;with c0 as
(
select REPLACE(@str, '"', '') + ',' as col0
), c1 as
(
select LEFT(col0, CHARINDEX(',', col0) - 1) as col1,
STUFF(col0, 1, CHARINDEX(',', col0), '') as col2
from c0
union all
select LEFT(col2, CHARINDEX(',', col2) - 1) as col1,
STUFF(col2, 1, CHARINDEX(',', col2), '') as col2
from c1
where LEN(col2) > 0
)
select col1 from c1 where col1 <> 'null'
或
;with c0 as
(
select @str as s
), c1 as
(
select number as n from master.dbo.spt_values where type = 'P'
)
select SUBSTRING(c0.s, c1.n, CHARINDEX(',', c0.s+',', c1.n)-c1.n) as item,
c1.n - LEN(REPLACE(LEFT(c0.s, c1.n), ',', '')) + 1 as pos1,
ROW_NUMBER() over(order by c1.n) as pos2,
c1.n, c0.s
from c0
inner join c1 on c1.n <= LEN(c0.s) and SUBSTRING(','+c0.s, c1.n, 1) = ','
或
set @str = 'select col1 = ''' + REPLACE(@str,',',''' union all select ''') + ''''
set @str = 'select col1 from (' + @str + ') as D'
exec(@str)
或
set @str = '(values (''' + REPLACE(@str,',',''' ),( ''') + ''')) as tb(item)'
set @str = 'select item from ' + @str
exec(@str)
在一次采访中,有人要求我通过替换特殊字符来转换字符串。
给定的字符串是 'AAA%BBB$CCC#DDD'
预期输出如图像所示:
我们如何在 SQL 服务器中执行此操作?提前致谢!
In SQL Server 2014?(我猜你用的操作系统是Windows Server 2008 R2,哈哈哈), 如果你使用SQL Server 2014-,基本上,你需要先统一不同的分隔符,
declare @str as varchar(1024) = 'AAA%BBB$CCC#DDD'
set @str = REPLACE(@str, '%', ',')
set @str = REPLACE(@str, '$', ',')
set @str = REPLACE(@str, '#', ',')
然后像这样:
;with c0 as
(
select REPLACE(@str, '"', '') + ',' as col0
), c1 as
(
select LEFT(col0, CHARINDEX(',', col0) - 1) as col1,
STUFF(col0, 1, CHARINDEX(',', col0), '') as col2
from c0
union all
select LEFT(col2, CHARINDEX(',', col2) - 1) as col1,
STUFF(col2, 1, CHARINDEX(',', col2), '') as col2
from c1
where LEN(col2) > 0
)
select col1 from c1 where col1 <> 'null'
或
;with c0 as
(
select @str as s
), c1 as
(
select number as n from master.dbo.spt_values where type = 'P'
)
select SUBSTRING(c0.s, c1.n, CHARINDEX(',', c0.s+',', c1.n)-c1.n) as item,
c1.n - LEN(REPLACE(LEFT(c0.s, c1.n), ',', '')) + 1 as pos1,
ROW_NUMBER() over(order by c1.n) as pos2,
c1.n, c0.s
from c0
inner join c1 on c1.n <= LEN(c0.s) and SUBSTRING(','+c0.s, c1.n, 1) = ','
或
set @str = 'select col1 = ''' + REPLACE(@str,',',''' union all select ''') + ''''
set @str = 'select col1 from (' + @str + ') as D'
exec(@str)
或
set @str = '(values (''' + REPLACE(@str,',',''' ),( ''') + ''')) as tb(item)'
set @str = 'select item from ' + @str
exec(@str)