I have lists like this stored in a field in SQL:
Id MyListField
1 soy, meat, milk, wheat, nuts
2 soy, meat, nuts, milk, wheat
3 nuts
4 walnuts, nutshell, nuts
5 nuts, beans
6 walnuts, hazel nuts
7 nutshell, nutsize
This is not normalized and I can't change it. I now have to find nuts
and replace them with insane
(but keep e. g. hazel nuts
and nutshell
).
A Find is relatively easy, there are four cases and I have the placeholder character %
at my disposal:
SELECT * FROM MyTable WHERE
MyListField LIKE 'nuts' OR
MyListField LIKE 'nuts, %' OR
MyListField LIKE '%, nuts' OR
MyListField LIKE '%, nuts, %'
But a Replace is hard, because I don't have placeholder or startofstring/endofstring characters:
UPDATE MyTable SET MyListField =
REPLACE(
REPLACE(
REPLACE(
REPLACE(
MyListField,
', nuts, ' ,
', insane, '
),
????,
????
),
????,
????
),
????,
????
)
WHERE
MyListField LIKE 'nuts' OR
MyListField LIKE 'nuts, %' OR
MyListField LIKE '%, nuts' OR
MyListField LIKE '%, nuts, %'
I can easily replace it in the middle of the string, but not at the start or the end. Or can I?
I am using SQL Server 2008, if that matters.