Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. SQL Server
  3. Question
SQL Server

How to solve SQL Server: Replace with wildcards?

Asked by Anne Bell May 27, 2024 4.8K views 3 answers
Share

About this question

 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 that can be used to bolt together a solution is there one something that does it more simply? For example REPLACE(data,'[xy]','q') to replace x or y with q.

Your answer

3 Answers

Ranjana Admin JanBask Expert Latest answer

Answered on Feb 7, 2025

In SQL Server, the REPLACE function does not support wildcards like % or _, as it performs a literal string replacement. If you need to replace text dynamically using wildcards, consider these approaches:

1. Use LIKE with CASE for Conditional Replacements

While REPLACE does not support wildcards, you can combine CASE with LIKE to handle different cases:

SELECT 
    CASE 
        WHEN column_name LIKE '%old_text%' THEN REPLACE(column_name, 'old_text', 'new_text') 
        ELSE column_name 
    END AS updated_column
FROM table_name;

This replaces old_text only if it exists within the column.

2. Using PATINDEX for Pattern Matching

If the replacement is based on patterns, PATINDEX can help identify positions:

SELECT STUFF(column_name, PATINDEX('%old_text%', column_name), LEN('old_text'), 'new_text')
FROM table_name;

This replaces only the first occurrence of old_text found within the string.

3. Using Regular Expressions (via CLR or External Scripts)

SQL Server does not support native regex, but you can use SQL CLR functions or external scripts (e.g., Python) to handle wildcard replacements.

4. Combine CHARINDEX and SUBSTRING for Complex Cases

If the replacement pattern is variable, use CHARINDEX to locate positions and SUBSTRING to rebuild the string.

If your scenario requires wildcard-based replacements, consider handling the logic in the application layer using programming languages like Python or C#.


Was this helpful?

More SQL Server discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest SQL Server Blogs

Guides, tips and career advice on SQL Server from JanBask experts.