2014-11-06 95 views
-1

我有'A9Tf6Uv54'字符串,现在我想用'xzxxzxxzz'格式替换它。用T-SQL中的字符和数字替换字符串中的字母

换句话说,字母字符被替换为'x'和数字'z'。

如何在SQL中用不同的字符替换数字和字母?

+1

你的问题并没有多大意义。尝试改写它,或者提供更多的输入/预期输出示例。 – GolfWolf 2014-11-06 14:52:44

+0

只要找到字母表,它必须用'x'和数字用'z'代替。请检查示例。 – Thej 2014-11-06 14:58:01

+0

请通过编辑您的问题来澄清您的问题。 – isherwood 2014-11-06 15:11:36

回答

2

你可以这样做:

DECLARE @StringText VARCHAR(20) = 'A9Tf6Uv54'; 
DECLARE @digitReplacement VARCHAR(20) = 'z'; 
DECLARE @letterReplacement VARCHAR(20) = 'x'; 

WHILE PATINDEX('%[^0-9'[email protected]+']%',@StringText)>0 
    SET @StringText = STUFF(@StringText,PATINDEX('%[^0-9'[email protected]+']%',@StringText),1,@letterReplacement) 
WHILE PATINDEX('%[0-9]%',@StringText)>0 
    SET @StringText = STUFF(@StringText,PATINDEX('%[0-9]%',@StringText),1,@digitReplacement) 


--RESULT 
xzxxzxxzz 
0

ifound错误并修复它 - :)

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)[email protected] 
set @[email protected] 
set @[email protected]+1 
end 
else 
begin 
set @str=ltrim(@str)[email protected] 
set @[email protected] 
set @[email protected]+1 
end 
end 
select @str 

>