我需要运行一个select语句来替换varchar列中的单个字符。列中的每个字符都将被更改。 A-Z需要改为A'并且0-9需要更改为' 0'。我想我理解如何使用正则表达式找到它们,但我不确定是否可以使用替换函数来执行此操作。实例
ABC123 > AAA000
Z15X97 > A00A00
这可以在tsql中完成而不使用substring一次更改一个字符,或者没有像replace(<column>, 'B','A')
这样的语句的列表(字母为25,字母为8)?
答案 0 :(得分:3)
这是一种方式,效率低但希望这只适用于一次性
CREATE TABLE tbl (id INT, txt VARCHAR(255));
INSERT tbl VALUES (1, 'ABC123'), (2, 'Z15X97'), (3, 'AZ09'), (4, '0123456789ABCXYZ')
;WITH T (id, txt, pos) AS (
SELECT id, CAST(txt AS VARCHAR(255)), 0 FROM tbl
UNION ALL
SELECT id,
CAST(STUFF(txt, pos + 1, 1, CASE WHEN SUBSTRING(txt, pos + 1, 1) LIKE '[A-Z]' THEN 'A' ELSE '0' END) AS VARCHAR(255)),
pos + 1
FROM T WHERE pos < LEN(txt)
)
SELECT id, txt
FROM T WHERE pos = LEN(txt)
id txt
4 0000000000AAAAAA
3 AA00
2 A00A00
1 AAA000
答案 1 :(得分:2)
试试这样:
if (DBIc_DBISTATE(imp_xxh)->debug >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), ">parse_params statement %s\n", statement);
结果
DECLARE @tbl TABLE(TestString VARCHAR(100));
INSERT INTO @tbl VALUES('ABC123'),('Z15X97');
WITH RunningNummbers AS
(
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS Inx
FROM (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS x(y)
CROSS JOIN (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS a(b)
CROSS JOIN (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS c(d) --1000 running numbers
)
SELECT TestString
,(
SELECT CASE WHEN SUBSTRING(tbl.TestString,Inx,1) BETWEEN 'A' AND 'Z' THEN 'A'
ELSE CASE WHEN SUBSTRING(tbl.TestString,Inx,1) BETWEEN '0' AND '9' THEN '0' ELSE SUBSTRING(tbl.TestString,Inx,1) END
END
FROM RunningNummbers
WHERE Inx<=LEN(tbl.TestString)
FOR XML PATH('')
) AS Replaced
FROM @tbl AS tbl