SQlite query to update column and replace a value

前端 未结 2 1560
说谎
说谎 2021-01-23 11:25

I want to update a column that contains a string like 12,43,433 I want to only replace 43 with another number say 54 so that the column value becomes 12,54,433.

How can

2条回答
  •  清酒与你
    2021-01-23 11:28

    Storing lists as strings is a very bad idea. SQL has a great data structure for storing lists. It is called a table, not a string. The proper way to store lists is to use a junction table.

    Sometimes we are stuck with other people's really bad design decisions. If so, you can do:

    update t
        set col = trim(replace(',' || col || ',', ',43,', ',54,'), ',')
        where ',' || col || ',' like '%,43,%';
    

    Notes:

    • This works regardless of where the "43" appears in the string (including at the beginning and end).
    • This maintains the format of the string with no commas at the beginning and end.
    • This only attempts to update rows that have the particular elements in the list.

    Use of such a query should really be a stopgap while you figure out how to fix the data structure.

提交回复
热议问题