在SQL中替换不可打印的Unicode字符

时间:2019-03-20 15:44:12

标签: sql sql-server unicode

Here is what I see in Notepad+++

我有一个正在使用的数据库,该数据库捕获了一些不可打印的Unicode字符(SS2或Single-Shift 2)。我在这里找到了一些应该用空格替换坏字符的函数,但是它们似乎没有用。这是我无法使用的内容:

我正在使用SQL Server 2017

CREATE FUNCTION [dbo].[strip_non_printable_characters] (@S nvarchar(max))
Returns nvarchar(max)
Begin
    ;with  cte1(N) As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
           cte2(C) As (Select Top (32) Char(Row_Number() over (Order By (Select NULL))-1) From cte1 a,cte1 b)
    Select @S = Replace(@S,C,' ')
     From  cte2

    Return ltrim(rtrim(replace(replace(replace(@S,' ','†‡'),'‡†',''),'†‡',' ')))
End

CREATE FUNCTION [dbo].[strip_non_printable_characters] (@input_string nvarchar(max))
returns table with schemabinding as return (
  select


replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(
replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(
replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(
replace(replace(@input_string collate Latin1_General_BIN,
    char(1), ''),char(2), ''),char(3), ''),char(4), ''),char(5), ''),char(6), ''),char(7), ''),char(8), ''),char(9), ''),char(10), ''),
    char(11), ''),char(12), ''),char(13), ''),char(14), ''),char(15), ''),char(16), ''),char(17), ''),char(18), ''),char(19), ''),char(20), ''),
    char(21), ''),char(22), ''),char(23), ''),char(24), ''),char(25), ''),char(26), ''),char(27), ''),char(28), ''),char(29), ''),char(30), ''),
    char(31), ''), char(0) , '') 
 as clean_string
);
go

运行这些功能中的任何一个时,字符串仍将显示SS2字符。如果我将其返回为NVARCHARvarchar的形式,则只会将错误字符显示为?。我需要用空格替换那个不好的角色。

有人可以告诉我我在做什么错吗?

谢谢!

更新

此功能满足了我的需求。

CREATE FUNCTION [dbo].[strip_non_printable_characters] (@OldString as nVarChar(4000))
RETURNS varChar(2000) AS  
BEGIN 
DECLARE @Count integer, @NewString varChar(4000)
SET @Count =1
SET @NewString = ''
WHILE @Count <= Len(@OldString)
BEGIN
    --If the character is not a regular ascii character it will be removed
    IF  UNICODE(SUBSTRING(@OldString,@Count,1)) < 127
        BEGIN
            SET @NewString  = @NewString + SUBSTRING(@OldString,@Count,1)
        END
    SET @Count = @Count + 1
END
RETURN @NewString
END

0 个答案:

没有答案