我有类似' A9Tf6Uv54
'的字符串,现在我想用' xzxxzxxzz
'替换它。格式。
换句话说,字母字符替换为' x
'和' z
'。
如何在SQL中用不同的字符替换数字和字母?
答案 0 :(得分:2)
你可以这样做:
DECLARE @StringText VARCHAR(20) = 'A9Tf6Uv54';
DECLARE @digitReplacement VARCHAR(20) = 'z';
DECLARE @letterReplacement VARCHAR(20) = 'x';
WHILE PATINDEX('%[^0-9'+@letterReplacement+']%',@StringText)>0
SET @StringText = STUFF(@StringText,PATINDEX('%[^0-9'+@letterReplacement+']%',@StringText),1,@letterReplacement)
WHILE PATINDEX('%[0-9]%',@StringText)>0
SET @StringText = STUFF(@StringText,PATINDEX('%[0-9]%',@StringText),1,@digitReplacement)
--RESULT
xzxxzxxzz
答案 1 :(得分:0)
ifound bug并修复它 - :)
declare @r int=1 --pointer to next letter in the string
declare @l int = (select len('A9Tf6Uv54'))
declare @str varchar(100)='' -- init the new str
declare @x varchar(10)='x' --replace number
declare @z varchar(10)='z' --replace char
while @l!=0 --loop ending at the end of the original str
begin
if (ascii(substring('A9Tf6Uv54',@r,1)) between 48 and 57)
begin
set @str=ltrim(@str)+@z
set @l=@l-1
set @r=@r+1
end
else
begin
set @str=ltrim(@str)+@x
set @l=@l-1
set @r=@r+1
end
end
select @str
>