删除特殊字符但不删除空格SQL

时间:2018-10-11 20:02:05

标签: sql-server tsql

此功能工作正常,但我试图保留空格。任何帮助将不胜感激

create function dbo.RemoveSpecialChars 
(@s varchar(256)) returns varchar(256)
   with schemabinding
begin
   if @s is null
      return null
   declare @s2 varchar(256)
   set @s2 = ''
   declare @l int
   set @l = len(@s)
   declare @p int
   set @p = 1
   while @p <= @l begin
      declare @c int
      set @c = ascii(substring(@s, @p, 1))
      if @c between 48 and 57 or @c between 65 and 90 or @c between 97 and 122
         set @s2 = @s2 + char(@c)
      set @p = @p + 1
      end
   if len(@s2) = 0
      return null
   return @s2
   end

2 个答案:

答案 0 :(得分:1)

您需要处理空格字符:

save

db<>fiddle demo

答案 1 :(得分:0)

几年前,我们解决了这个问题。您需要的是PatReplace8k的副本。对于这种情况,它是最快的功能,几乎没有秒。请注意示例:

-- Example 1: Against a variable
DECLARE @string VARCHAR(8000) = '#$!^@#%! Blah blah blah (^&@(#&@!';

SELECT string = @string, f.NewString
FROM   samd.patReplace8k(@string, '[^a-zA-Z ]','') AS f

-- Example 2: Using APPLY against a table
DECLARE @table TABLE(somestring VARCHAR(256)); 
INSERT  @table VALUES('ABC123 !!!! Hi'), ('&&&&&Letters here^^^^^^^^^');

SELECT t.somestring, f.NewString
FROM   @table AS t
CROSS APPLY samd.patReplace8K(t.somestring,'[^a-zA-Z ]','') AS f;

结果:

string                                       NewString
-------------------------------------------- ----------------
#$!^@#%! Blah blah blah (^&@(#&@!             Blah blah blah 

somestring                                   NewString
-------------------------------------------- ----------------
ABC123 !!!! Hi                               ABC  Hi
&&&&&Letters here^^^^^^^^^                   Letters here

通常-您不惜一切代价避免使用T-SQL标量用户定义函数!他们总是表现糟糕,并有许多错误和其他问题。 ITVF is the only way to go - Always