REPLACE function enables us to look for a certain character phrase in a string and replace it with another character phrase. The updated string is then returned by the function.
The syntax for this string function is the same for SQL Server, Oracle and Microsoft Access. The syntax is as follows:
REPLACE(stringToLookIn, stringToMatch, replacementsString)
The syntax is fairly straight forward, the stringToMatch parameter is the character phrase that we want to replace, the replacementsString is the character phrase that will replace any occurence of the stringToMatch parameter. If the stringToMatch phrase occurs more than once in the string, then all instances of the phrase will be replaced with the replacement string. If no matches were found then the string is returned unaltered.
If we want to match multiple items, we need to nest the
REPLACE(REPLACE(stringToLookIn, stringToMatch, replacementsString), stringToMatch, replacementsString)
or set the replaced string into a new variable multiple times:
stringReturned = REPLACE(stringToLookIn, stringToMatch, replacementsString) stringReturned = REPLACE(stringReturned, stringToMatch, replacementsString)
This is far from ideal, especially the more strings there are to be matched. This is where User-Defined Functions (UDFs) can provide the answer.
A User-Defined Function, is a function provided by the user of a program or environment. In SQL databases, a user-defined function provides a mechanism for extending the functionality of the database server by adding a function that can be evaluated in SQL statements.
The Function Code
Below is the complete function definition:
CREATE FUNCTION dbo.udf_ReplaceChars ( @ReplaceList VARCHAR(50), @String VARCHAR(100) ) RETURNS VARCHAR(100) AS BEGIN DECLARE @CHAR CHAR(1), @Loop INT SET @Loop = 0 WHILE @Loop < = LEN(@ReplaceList) BEGIN SET @Loop = @Loop + 1 SET @CHAR = SUBSTRING(@ReplaceList, @Loop, 1) SET @String = REPLACE(@String, @CHAR, '') END RETURN @String END GO
The function simply loops over the replace list, finding each instance of the list item in the string in which we want to replace items. The new string is then returned out of the function.
The Function In Use
A very simple use of the replace function could be as follows:
SELECT dbo.udf_ReplaceChars('=,/,<,>,@,~,#', columnName) AS newColumn, columnName FROM tableName
The function is not restricted to
SELECT statements. Below is an example of an
UPDATE statement utilising a variable:
UPDATE tableName SET columnName = dbo.udf_ReplaceChars('=,/,<,>,@,~,#', @variableName) WHERE idName = @myId
Download the Code
Download the code, rename the file to .sql and run on your database instance. You will then be able to reference the function in your Stored Procedures.