【问题标题】:Remove special characters but not spaces SQL删除特殊字符但不删除空格 SQL
【发布时间】:2018-10-11 20:02:04
【问题描述】:

这个功能很好用,但我想保留空格。任何帮助将不胜感激

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

【问题讨论】:

  • 可能加or @c = 32
  • 您使用的是哪个 dbms? (该代码是特定于产品的。)
  • 微软 sql 服务器
  • Re: set @l = len(@s) From Len(): "返回指定字符串表达式的字符数,不包括尾随空格。" DataLength 不排除尾随空格。对于 Unicode 字符串,您可以使用 DataLength( UnicodeStringExpression ) / DataLength( N'#' ) 来获取字符长度。一般DataLength( Left( Coalesce( StringExpression, '#' ), 1 ) ) 会返回每个字符的字节数。
  • 没有其他方法那么快,但在处理re-coding of accented characters to plain latin 时非常强大。您可能必须针对给定的排序规则调整这种方法...

标签: sql-server


【解决方案1】:

你需要处理空格字符:

if @c between 48 and 57 or @c between 65 and 90 or @c between 97 and 122 
   or @c = ASCII(' ')

db<>fiddle demo

【讨论】:

    【解决方案2】:

    我们几年前就解决了这个问题。您需要的是一份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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-12
      • 1970-01-01
      • 2020-03-16
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      相关资源
      最近更新 更多