Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL for replace with wildcard

Tags:

replace

sql

mysql

I'm trying to write a SQL update to replace a specific xml node with a new string:

UPDATE table
SET Configuration = REPLACE(Configuration,
     "<tag>%%ANY_VALUE%%</tag>"
     "<tag>NEW_DATA</tag>");

So that

<root><tag>SDADAS</tag></root>

becomes

<root><tag>NEW_DATA</tag></root>

Is there a syntax im missing for this type of request?

like image 525
tinkertime Avatar asked Jan 08 '14 16:01

tinkertime


People also ask

Can you use wildcard in replace SQL?

The REPLACE built-in function does not support patterns or wildcards; only LIKE and PATINDEX 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: SELECT REPLACE( REPLACE('A B x 3 y Z x 943 yy!

Can we use wildcard in MySQL?

MySQL WildcardsA wildcard character is used to substitute one or more characters in a string. Wildcard characters are used with the LIKE operator. The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

What's the difference between _ and in SQL wildcard?

What's the difference between _ and in SQL wildcard? % (Percentage) – Using this wildcard operator, we can match from 0 upto many characters in a string or column's value. _ (Underscore) – Using this wildcard operator, we can only match one character in a string or column's value.


1 Answers

Update: MySQL 8.0 has a function REGEX_REPLACE().

Below is my answer from 2014, which still applies to any version of MySQL before 8.0:


REPLACE() does not have any support for wildcards, patterns, regular expressions, etc. REPLACE() only replaces one constant string for another constant string.

You could try something complex, to pick out the leading part of the string and the trailing part of the string:

UPDATE table
SET Configuration = CONCAT(
      SUBSTR(Configuration, 1, LOCATE('<tag>', Configuration)+4),
      NEW_DATA,
      SUBSTR(Configuration, LOCATE('</tag>', Configuration)
    )

But this doesn't work for cases when you have multiple occurrences of <tag>.

You may have to fetch the row back into an application, perform string replacement using your favorite language, and post the row back. In other words, a three-step process for each row.

like image 154
Bill Karwin Avatar answered Oct 21 '22 07:10

Bill Karwin