Replace specific value in comma separated list using SQL
P粉248602298
2023-08-08 17:29:43
<p>I need to replace specific values in a comma separated list. </p>
<p>For example, suppose I have a column named Tags, populated with the following content: Holidays, Holidays 2023, Test. </p>
<p>I only need to replace the word 'Holidays' with 'Holiday', but I don't want to replace 'Holidays 2023' with 'Holiday 2023'. </p>
<p>I tried using the replace function and LIKE in the WHERE clause, but it didn't work. I'm using PHP as backend, but I don't know how to avoid this. </p>
<p>The following is the SQL I use:</p><p>
<code>UPDATE Expenses SET Tags = REPLACE(Tags, :original, :replace), Updated_date = :update_date WHERE Id_user = :id_user AND Tags LIKE :original_like</code></p>
<ul>
<li><em>:original</em> contain the list: <strong>Holidays, Holidays 2023, Test</strong></li>
<li><em>:replace</em> contain only the word <strong>Holiday</strong></li>
</ul><p><br /></p>
Add a leading comma and space before your value, then add a trailing comma - then replace , Holidays, with , Holiday,.
nRemove leading and trailing commas in the result again afterwards
Example of using specific values
No Holidays, Holidays, Holidays 2023, Holidays, Test, Holidays
inserted directly instead of getting it from the holidays column:The result will be: