SQL - 替换字符串中的非数字字符

时间:2013-07-19 08:23:53

标签: sql string replace character

我正在编写一个带字符串的函数,必须用从表中取出的两个数字字符替换任何非数字字符。这是我用来探索字符串并找到非数字字符的代码:

SET @string = '1a2b3c4d'
SET @wcount= 0
SET @index = 1
SET @len= LEN(@string)

WHILE @index<= @len
 BEGIN
    SET @char = SUBSTRING(@string, @index, 1)
    IF @char LIKE '%[a-z]%'
      PRINT 'char ' + CONVERT(varchar(10), @index)
    ELSE
      PRINT @char
    SET @index= @index+ 1
 END

输出如下

1
char 2
2
char 4
3
char 6
4
char 8

现在,当我找到一个非数字字符时,我必须将它替换为两个从select中取出的数字字符。 E.g。

SELECT @temp = REPLACEMENT FROM Conversion_Tab WHERE EXPR = @char

总之,如果我有以下字符串'1a2a3a4a'并且'a'的替换为'88',则结果字符串应为'188288388488'

提前感谢您的帮助。

再见!

2 个答案:

答案 0 :(得分:2)

试试这个

DECLARE @string VARCHAR(100)
DECLARE @outstring VARCHAR(100)
DECLARE @wcount INT
DECLARE @temp INT
DECLARE @index INT
DECLARE @len INT
DECLARE @char CHAR

SET @string = '1a2a3a4a'
SET @wcount= 0
SET @index = 1
SET @len= LEN(@string)

SET @outstring = ''

WHILE @index<= @len
 BEGIN
    SET @char = SUBSTRING(@string, @index, 1)
    IF @char LIKE '%[a-z]%'
    BEGIN
      SELECT @temp = REPLACEMENT FROM #Conversion_Tab WHERE EXPR = @char
      SET @outstring = @outstring + CONVERT(VARCHAR(10),@temp)
     END
    ELSE
    BEGIN
      SET @outstring = @outstring + @char 
    END
    SET @index= @index+ 1

END

SELECT @outstring

SQL FIDDLE DEMO

答案 1 :(得分:0)

看起来你需要isnumeric()。所以如果不是isnumeric(char)用你的查找值替换它。

取自另一个答案但产生相同的结果

DECLARE @string VARCHAR(100)
DECLARE @outstring VARCHAR(100)
DECLARE @wcount INT
DECLARE @temp INT
DECLARE @index INT
DECLARE @len INT
DECLARE @char CHAR

SET @string = '1a2a3a4a'
SET @wcount= 0
SET @index = 1
SET @len= LEN(@string)

SET @outstring = ''

WHILE @index<= @len
 BEGIN
    SET @char = SUBSTRING(@string, @index, 1)
    IF ISNUMERIC(@char) = 0
    BEGIN
      SELECT @temp = REPLACEMENT FROM #Conversion_Tab WHERE EXPR = @char
      SET @outstring = @outstring + CONVERT(VARCHAR(10),@temp)
     END
    ELSE
    BEGIN
      SET @outstring = @outstring + @char 
    END
    SET @index= @index+ 1

END