search

Home  >  Q&A  >  body text

Replace specific value in comma separated list using SQL

<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>
P粉248602298P粉248602298484 days ago490

reply all(1)I'll reply

  • P粉180844619

    P粉1808446192023-08-09 16:23:28

    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

    SELECT TRIM(',' FROM REPLACE(CONCAT(', ', Tags, ','), ', Holidays,', ', Holiday,'))

    Example of using specific values ​​No Holidays, Holidays, Holidays 2023, Holidays, Test, Holidays inserted directly instead of getting it from the holidays column:

    SELECT TRIM(',' FROM REPLACE(
      CONCAT(', ', 'No Holidays, Holidays, Holidays 2023, Holidays, Test, Holidays', ','),
      ', Holidays,',
      ', Holiday,')
    )

    The result will be:

    No Holidays, Holiday, Holidays 2023, Holiday, Test, Holiday

    reply
    0
  • Cancelreply