Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Sql Query to search and replace specific prefixed strings?

Alright I have something like this(I messed it up...) -

Id Name                     City
1  XXX - New                Plano
2  XXX - XXX - New1         Dallas
3  XXX - XXX - XXX - New2   Sacramento
4  XXX - New3               Houston
5  XXX - XXX - New4         Austin

So, I want to replace all the occurrence with more that one XXX prefix to just 1. For e.g id 2 should have Name=XXX - New2. How would go about achieving this ? Even a query basically to check for a prefix and replace it with the name would work I think and then I can add the prefix again ? I mean set all the records just to say New,New2..so on...and then I can add XXX prefix to it ?

like image 356
Vishal Avatar asked Jan 28 '11 18:01

Vishal


People also ask

How do I replace a specific string 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.

How do I change a prefix in SQL?

To remove this prefix of 'MR. ', we need to use the keywords UPDATE, SET, RIGHT, LEN, and WHERE. The following command updates the entry of the column starting with 'MR. ' with a substring of the name extracted using RIGHT keyword.

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.

How do I remove a specific string from a string in SQL?

The TRIM() function removes the space character OR other specified characters from the start or end of a string. By default, the TRIM() function removes leading and trailing spaces from a string. Note: Also look at the LTRIM() and RTRIM() functions.


1 Answers

You can remove all instances of 'XXX - ' with the string replace function.

UPDATE tableName
SET Name = Replace(Name, 'XXX - ', '')

Alternately, to keep a single instance you could use:

UPDATE tableName
SET Name = 'XXX - ' + Replace(Name, 'XXX - ', '')
WHERE CHARINDEX('XXX - ', Name) > 0
like image 127
nybbler Avatar answered Sep 30 '22 13:09

nybbler