Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform regex (replace) in an SQL query

What is the best way to replace all '&lt' with < in a given database column? Basically perform s/&lt[^;]/</gi

Notes:

  • must work in MS SQL Server 2000
  • Must be repeatable (and not end up with <;;;;;;;;;)
like image 718
alumb Avatar asked Sep 29 '08 22:09

alumb


People also ask

Can you use RegEx in SQL replace?

Yes, the results in the result pane can quickly be turned into HTML or SQL Insertion code using a RegEx search and replace, though this is often easiest done in a more specialised programmers' text editor.

How do you replace a pattern in SQL?

The REPLACE() function replaces all occurrences of a substring within a string, with a new substring. Note: The search is case-insensitive.

How find and replace in SQL query?

On the Edit menu, point to Find and Replace, and then click Quick Replace to open the dialog box with both find options and replace options. Toolbar buttons and shortcut keys are also available to open the Find and Replace dialog box.


1 Answers

Some hacking required but we can do this with LIKE, PATINDEX, LEFT AND RIGHT and good old string concatenation.

create table test
(
    id int identity(1, 1) not null,
    val varchar(25) not null
)

insert into test values ('&lt; <- ok, &lt <- nok')

while 1 = 1
begin
    update test
        set val = left(val, patindex('%&lt[^;]%', val) - 1) +
                      '&lt;' +
                      right(val, len(val) - patindex('%&lt[^;]%', val) - 2)
    from test
    where val like '%&lt[^;]%'

    IF @@ROWCOUNT = 0 BREAK
end

select * from test

Better is that this is SQL Server version agnostic and should work just fine.

like image 162
Jorge Ferreira Avatar answered Oct 06 '22 13:10

Jorge Ferreira