Pages

Showing posts with label remove unwanted characters. Show all posts
Showing posts with label remove unwanted characters. Show all posts

Tuesday, August 6, 2013

Remove Special Characters from String or Columns in SQL server

STEP 1: Create function "GetCharacters" which removes the unwanted characters.

Parameters:
@myString contains the columns values
@validChars contains the valid chars which u want and all remains are filtered.


Create function dbo.GetCharacters(@myString varchar(max), @validChars varchar(500))
RETURNS varchar(500) AS
BEGIN
While @myString like '%[^' + @validChars + ']%'
Select @myString = replace(@myString,substring(@myString,patindex('%[^' + @validChars + ']%',@myString),1),'')
Return @myString
END
Go



STEP 2: Create function "GetTable" which returns the filtered values in table form.


Create function GetTable(@ValidCharacters varchar(max))
RETURNS @MyTable TABLE
   (
    Result varchar(max)
   )
AS
BEGIN
INSERT INTO @MyTable (Result)
SELECT dbo.GetCharacters(address,@ValidCharacters) as Result
FROM tab_booking
RETURN

END
GO

 

Here, 
 "tab_booking" is the table.
"address" is the column which filtered.

STEP 3: Call function "GetTable"
  
 SELECT * FROM dbo.GetColumns('a-z0-9@$%')

Here 0 to 9,A to Z, @, $, % are the characters which u want.


 NOTE: *Copy the Red Code and Execute Step wise.
 *Use your own Database,tables,columns.
*execute for once step 1 & step 2 queries to create functions.
* then at last, To Get the Result execute step 3 red code any no. of times.
*if u want to make any change in the functions after create it once, then replace "Create" by "Alter" like this:
 Create function GetTable(@ValidCharacters varchar(max))

  Alter function GetTable(@ValidCharacters varchar(max))