Does Microsoft SQL Server natively support some sort of replace
function using wild cards? I gather that Regular Expressions are not available natively.
I note that there is a PATINDEX
function which can be used to bolt together a solution — is there one something which does it more simply?
For example REPLACE(data,'[xy]','q')
to replace x
or y
with q
.
Best Answer
The
REPLACE
built-in function does not support patterns or wildcards; onlyLIKE
andPATINDEX
do.Assuming that you really just want the simple single-character replacement as shown in the question, then you can call
REPLACE
twice, one nested in the other, as follows:Returns:
If you do need more complex pattern matching / replacement, then you will need to do that via Regular Expressions, which can only be done via SQLCLR. Several SQLCLR RegEx functions are available in the Free version of the SQL# SQLCLR library (which I wrote), one of them being
RegEx_Replace[4k]()
(the4k
version is for when you are certain that you will never need more than 4000 characters, hence you can get better performance from not usingNVARCHAR(MAX)
as an input parameter or return value).The equivalent of the two nested
REPLACE
calls would be done as follows (and using the pattern syntax shown in the question):Returns:
But, since we are talking about the possibility of a more complex pattern, one that cannot be done easily in T-SQL, we can use a quantifier on the pattern to have it replace any number of contiguous
x
ory
characters with a singleq
:Returns:
Please note that the input string was changed slightly from the previous two examples to add an extra
x
after theZ
, and to add an extraxxyxy
to theyy
at the end. And, in both cases, the multi-character fragment was replaced with a singleq
.For more info on working with strings and collations, please visit: Collations Info