如何通过sql查询替换给定字符串中的特定字符数?

时间:2013-03-01 15:02:50

标签: sql-server

像:

s1= 'ldoed@dldkeo@fkfok@dkf@'

输出如'ldoedKdldkeo @ fkfokKdkf @'

将第一个@和第三个@替换为字符串'K'

1 个答案:

答案 0 :(得分:3)

使用charindex()stuff()

尝试此操作

Fiddle demo 1

declare @s1 varchar(100)= 'ldoed@dldkeo@fkfok@dkf@', @count int = 0 

select @count = charindex('@',@s1,@count+1), 
       @s1 = case isremove when 1 then 
             stuff(@s1, charindex('@',@s1,@count) ,1,'K') else @s1 end
from (values (1),(0),(1)) t(isremove)

Fiddle demo 2

declare @s1 varchar(100)= 'ldoed@dldkeo@fkfok@dkf@'

select stuff(stuff(@s1,first,1,'K'),third,1,'K')
from (
select charindex('@',@s1,1) first,
   charindex('@',@s1,charindex('@',@s1,charindex('@',@s1,1)+ 1)+1) third
)x