我有contact_firstname列,在该列中存储的数据中有一些特殊字符,如(@,&, - ,_等)。我想首先在每个记录中找到所有这些特殊字符,并用空格替换这些字符。我在这个网站上找到了一个查询,它有助于识别特殊字符,但我不知道如何在下面的字符串中找到每个特殊字符的charindex并用空格替换它。
DECLARE @MyString VARCHAR(100)
SET @MyString = '!Char$Fox@'
IF (@MyString LIKE '%[^a-zA-Z0-9]%')
BEGIN
PRINT 'Contains "special" characters'
END
答案 0 :(得分:0)
我认为你必须循环,正如Tab Alleman所说:
declare @MyString varchar(100) = '!Char$Fox@'
declare @i int = 0
declare @char varchar(1)
declare @len int = LEN(@MyString)
declare @result varchar(100) = ''
while @i < @len
begin
set @char = SUBSTRING(@MyString, @i, 1)
if @char like '%[^a-zA-Z0-9]%'
begin
set @char = ' '
end
set @result = @result + @char
set @i = @i + 1
end
select @result
答案 1 :(得分:0)
你也可以这样做:
DECLARE @InvalidChars VARCHAR(100)
DECLARE @MyString VARCHAR(100)
SET @InvalidChars = '!$@'
SET @MyString = '!Char$Fox@'
;WITH CTE AS
(
SELECT SUBSTRING(@InvalidChars, 1, 1) AS [String], 1 AS [Start], 1 AS [Counter]
UNION ALL
SELECT SUBSTRING(@InvalidChars, [Start] + 1, 1) AS [String], [Start] + 1, [Counter] + 1
FROM CTE
WHERE [Counter] < LEN(@InvalidChars)
)
SELECT @MyString = REPLACE(@MyString, CTE.[String], ' ') FROM CTE
SELECT @MyString
结果:
Char Fox
这是以下解决方案的组合:
How to Replace Multiple Characters in SQL?
T-SQL: Opposite to string concatenation - how to split string into multiple records [duplicate]