0

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

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 @temp = REPLACEMENT FROM Conversion_Tab WHERE EXPR = @char

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

提前感谢您的帮助。

再见!

4

2 回答 2

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 小提琴演示

于 2013-07-19T08:43:42.287 回答
0

看起来你需要 isnumeric()。因此,如果不是 isumeric(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
于 2013-07-19T08:44:40.740 回答