REPLACE (Transact-SQL)
Replaces all occurrences of a specified string value with another string value.
REPLACE performs comparisons based on the collation of the input. To perform a comparison in a specified collation, you can use COLLATE to apply an explicit collation to the input.
The following example replaces the string cde in abcdefghi with xxx.
SELECT REPLACE('abcdefghicde','cde','xxx');
GO
Here is the result set.
------------ abxxxfghixxx (1 row(s) affected)
The following example uses the COLLATE function.
SELECT REPLACE('Das ist ein Test' COLLATE Latin1_General_BIN,
'Test', 'desk' );
GO
Here is the result set.
------------ Das ist ein desk (1 row(s) affected)
Replace Group of Characters
@original - You can use regex instead of nesting your REPLACE's.
CREATE FUNCTION [dbo].[removeStringCharacters]
/*
Author: Cameron Usman
Date: 2011-09-13
UDF Fuction that returns passed in @string value after removing any characters found in @remove
@remove can be anything that can be contained within [@remove] to be used as regex
Sample Call
SELECT dbo.removeStringCharacters('ABCD.1234,zyxw-0_987*','.,-_*')
*/
(
@string varchar(max)
, @remove varchar(100)
)
RETURNS varchar(max)
AS
BEGIN
WHILE @string LIKE '%[' + @remove + ']%'
BEGIN
SET @string = REPLACE(@string,SUBSTRING(@string,PATINDEX('%[' + @remove + ']%',@string),1),'')
END
RETURN @string
END
CREATE FUNCTION [dbo].[removeStringCharacters]
/*
Author: Cameron Usman
Date: 2011-09-13
UDF Fuction that returns passed in @string value after removing any characters found in @remove
@remove can be anything that can be contained within [@remove] to be used as regex
Sample Call
SELECT dbo.removeStringCharacters('ABCD.1234,zyxw-0_987*','.,-_*')
*/
(
@string varchar(max)
, @remove varchar(100)
)
RETURNS varchar(max)
AS
BEGIN
WHILE @string LIKE '%[' + @remove + ']%'
BEGIN
SET @string = REPLACE(@string,SUBSTRING(@string,PATINDEX('%[' + @remove + ']%',@string),1),'')
END
RETURN @string
END
- 6/14/2011
- Xian - ITManx
- 9/13/2011
- Cameron Usman
