Search

Showing posts with label Replace. Show all posts
Showing posts with label Replace. Show all posts

Wednesday, December 14, 2011

Remove unwanted characters from a string


Sometime it is required to remove some part of string from a string and replace that with some other string. The replace function will help you solve the problem when you need to remove or replace string values from your specified queries results.
Example:

SELECT REPLACE ([ContactName], 'M','') AS ContactNamesNoM
FROM [Northwind].[dbo].[Customers]
This will return ContactNames where M in ContactNames will be replaced by white space.

The Syntax goes as:

REPLACE ( string_expression , string_pattern , string_replacement )

Saturday, January 15, 2011

When to use STUFF instead of REPLACE – SQL Server

The STUFF function in SQL Server ‘inserts’ a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.
REPLACE on the other hand replaces all occurrences of a specified string value with another string value.
The STUFF function is useful when you are not sure of the characters to replace, but you do know the position of the character. I saw an excellent implementation of this function overhere by GMastros and Even. Here’s the code with a practical usage of STUFF:
CREATE FUNCTION [dbo].[fn_StripCharacters](    @String NVARCHAR(MAX),    @MatchExpression VARCHAR(255))RETURNS NVARCHAR(MAX)ASBEGIN    SET @MatchExpression =  '%['+@MatchExpression+']%'    WHILE PatIndex(@MatchExpression, @String) > 0        SET @String = STUFF(@String, PatIndex(@MatchExpression,@String), 1, '')    RETURN @StringENDSELECT dbo.fn_StripCharacters('a1$%s#22d&39#f4$', '^a-z')as OnlyAlphabets