Search This Blog

Thursday, July 26, 2012

Stripping special characters from SQL text

Reposting only to keep this from disappearing.  Simple redundancy and I do not claim any part of this work as my known.


This is a repost from Sean McWherter's blog.  

Excerpt from his blog:
Was looking for a better solution than a mile long REPLACE statement, found this. Originally written by Christian d’Heureuse, modified slightly by me. Removes all characters except: 0-9, a-z, A-Z, and spaces (remove “or @c = 32” if you want to also remove spaces).

Here is my usage.  Only added fx_ to function name.

CREATE function dbo.fx_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 or @c = 32
         set @s2 = @s2 + char(@c)
      set @p = @p + 1
      end
   if len(@s2) = 0
      return null
   return @s2
   end


1 comment:

rudraksh said...

Hey,

Thanks for sharing this blog its very helpful to implement in our work




Regards.

hacker for hire