Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I do a find/replace in t-sql?

Tags:

I basically have an xml column, and I need to find and replace one tag value in each record.

like image 642
Joel Martinez Avatar asked Oct 05 '08 03:10

Joel Martinez


People also ask

Can you find and replace in SQL?

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.

How do I create a replace in SQL?

The basic syntax of replace in SQL is: REPLACE(String, Old_substring, New_substring); In the syntax above: String: It is the expression or the string on which you want the replace() function to operate.

How do you replace a character in a column in SQL Server?

If you'd like to replace a substring with another string, simply use the REPLACE function. This function takes three arguments: The string to change (which in our case was a column). The substring to replace.

How do you replace multiple values in SQL?

SELECT REPLACE(REPLACE(REPLACE(REPLACE('3*[4+5]/{6-8}', '[', '('), ']', ')'), '{', '('), '}', ')'); We can see that the REPLACE function is nested and it is called multiple times to replace the corresponding string as per the defined positional values within the SQL REPLACE function.


1 Answers

For anything real, I'd go with xpaths, but sometimes you just need a quick and dirty solution:

You can use CAST to turn that xml column into a regular varchar, and then do your normal replace.

UPDATE xmlTable SET xmlCol = REPLACE( CAST( xmlCol as varchar(max) ), '[search]', '[replace]')

That same technique also makes searching XML a snap when you need to just run a quick query to find something, and don't want to deal with xpaths.

SELECT * FROM xmlTable WHERE CAST( xmlCol as varchar(max) ) LIKE '%found it!%'

Edit: Just want to update this a bit, if you get a message along the lines of Conversion of one or more characters from XML to target collation impossible, then you only need to use nvarchar which supports unicode.

CAST( xmlCol as nvarchar(max) )

like image 123
Cory Mawhorter Avatar answered Oct 05 '22 09:10

Cory Mawhorter