3

Is it possible to replace a specific part of a string with another? E.g. I have a column which holds a path to a file, I renamed the folder download portal (on my physical harddrive) to download_portal, so I have to change the path in thousands of database records.

Example record before and after:

/fileadmin/download portal/test/myfile.jpg

after:

/fileadmin/download_portal/test/myfile.jpg

Let's assume this is my table fruits:

id | path
1  | /fileadmin/download portal/test/apple.jpg
2  | /fileadmin/download portal/test/banana.jpg
3  | /fileadmin/download portal/test/pineapple.jpg

How can I change download portal to download_portal in every record by using SQL? Can I solve it by using regular expressions?

2
  • read about replace funtion. Please add the dbms tag which you are using Commented Jun 23, 2017 at 7:02
  • replace? Commented Jun 23, 2017 at 7:04

2 Answers 2

10

I don't think you necessarily need a regex replacement here. Just a normal replacement of download portal to download_portal should work. The following UPDATE should work on most databases:

UPDATE fruits
SET path = REPLACE(path, '/download portal/', '/download_portal/')
WHERE path LIKE '%/download portal/%'

Note: I think searching for /download portal/ is more restrictive, and safer, than just the plain text. This is so because it eliminates the chance of accidentally replacing download portal which appears as part of some other larger path name.

Sign up to request clarification or add additional context in comments.

2 Comments

That worked thx! I wonder If this would also work with regular expressioins.
If you're actually using MySQL, then the answer is no, because MySQL does not support regex replacement, at least not without writing your own user-defined function. You got lucky, perhaps, because normal replacements should cover your use case.
1

If you are using SSMS you can use REPLACE Function to get what you want.

Update tableName SET ColumnToChange = Replace(ColumnToChange, 'x_name','x_myname')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.