I wish to write an SQL statement for SQL Server 2008 that Selects entry's where a column contains a value, now the value within the column is a comma delimited list (usually - there could only be one entry (and no leading comma)) so what In checking for is "is this value contained somewhere within the list?", for instance:
COLUMN = Cat, Dog, Sparrow, Trout, Cow, Seahorse Does COLUMN contain Cat? YES Does COLUMN contain horse? NO Does COLUMN contain Sheep? NO
or
COLUMN = Mouse Does COLUMN contain Hare? NO Does COLUMN contain Mouse? YES
etc
I was thinking I could use the 'IN' keyword as such
SELECT id_column FROM table_name WHERE 'Cat' IN COLUMN
but this does not work as it seems that you can only use that to check if a column contains one of a series of comma delimited values.
I also cannot use CONTAINS() OR 'LIKE' as this, in the above example would return values for 'horse' as the whole string contains horse in 'Seahorse', and I can't search for the needle plus a comma (if I'm looking for 'horse' the search would be 'horse,') as what if the entry is at the end of a the list? And I can't search for a comma plus a needle (if I'm looking for 'horse' the search would be ',horse') as what if the entry is the first in the list? And I can't use both as what if the entry is the only (single) entry?
To check if value exists in a comma separated list, you can use FIND_IN_SET() function. Now you can insert some records in the table using insert command. Display all records from the table using select statement.
Special characters such as commas and quotes must be "escaped," which means you place a backslash in front of the character to insert the character as a part of the MySQL string.
To perform where clause on comma separated string/values, MySQL has an inbuilt function called FIND_IN_SET which will search for values within a comma separated values. You can also use IN operator to achieve the same but there are some limitations with IN operator which I will show below.
There is one tricky scenario. If I am looking for '40' in the list '17,34,400,12' then it would find ",40" and return that incorrect entry. This takes care of all solutions:
WHERE (',' + RTRIM(MyColumn) + ',') LIKE '%,' + @search + ',%'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With