Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace a pattern using T-SQL?

I have code to normalize a POB address. For example, one of the normalizations included is:

set @string = replace(@string, 'pobox', 'pob')

Now I want to do something similar: I want to find any POB that is directly followed by a number (without a space in between) and insert a space. I want to find the pattern like POB[0-9] and then replace the "POB" with "POB ". How can I accomplish this? Can it be done with a simple replace? Or do I need to use some other function, like PATINDEX?

like image 918
froadie Avatar asked Dec 08 '10 08:12

froadie


People also ask

How do you replace a pattern in SQL?

SQL Server REPLACE() FunctionThe REPLACE() function replaces all occurrences of a substring within a string, with a new substring. Note: The search is case-insensitive. Tip: Also look at the STUFF() function.

Does T SQL support RegEx?

We use regular expressions to define specific patterns in T-SQL in a LIKE operator and filter results based on specific conditions. We also call these regular expressions as T-SQL RegEx functions. In this article, we will use the term T-SQL RegEx functions for regular expressions.

Can I use RegEx to replace in SQL?

Description. The Oracle/PLSQL REGEXP_REPLACE function is an extension of the REPLACE function. This function, introduced in Oracle 10g, will allow you to replace a sequence of characters in a string with another set of characters using regular expression pattern matching.


1 Answers

Yes you are correct you can use PATINDEX

Declare @searchstring varchar(50)

Set @searchstring = 'POB9090'

If (PatIndex('POB[0-9]%', @searchString) > 0)
Begin

Set @searchstring = Replace(@searchString, 'POB', 'POB ')

End

Select @searchString

Or probably a nicer way would be to use a case statement so that it can be easily incorporated in to a select statement

Declare @searchstring varchar(50)

Set @searchstring = 'POB9090'

Select Case
        When PatIndex('POB[0-9]%', @searchString) > 0 Then Replace(@searchString, 'POB', 'POB ')
        Else @searchString
        End 'SearchString'
like image 132
codingbadger Avatar answered Sep 21 '22 03:09

codingbadger