Tuesday, September 29, 2009

How to Remove Special Characters from Text String in MS SQL (T-SQL)

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).
/****** Object:  UserDefinedFunction [dbo].[RemoveSpecialChars]    Script Date: 09/29/2009 09:48:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
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 or @c = 32
         set @s2 = @s2 + char(@c)
      set @p = @p + 1
      end
   if len(@s2) = 0
      return null
   return @s2
   end

1 comment: