SQlite query to update column and replace a value

牧云@^-^@ 提交于 2020-02-16 03:52:32

问题


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 I do that??


回答1:


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.




回答2:


You can use REPLACE() function like this:

UPDATE YourTable a
SET a.StringColumn = REPLACE(a.StringColumn,',43,',',54,')
WHERE a.StringColumn like '%,43,%'


来源:https://stackoverflow.com/questions/35480041/sqlite-query-to-update-column-and-replace-a-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!