Hi I am wondering how 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?
Thanks for any help anyone can give.
Cheers.
This will of course require a full table scan for every search.
Where value in column containing comma delimited values search with multiple comma delimited
Although the tricky solution @tbaxter120 advised is good but I use this function and work like a charm, pString is a delimited string and pDelimiter is a delimiter character:
Then for example you can call it in where clause as below:
Hope this help.
The best solution in this case is to normalize your table to have the comma separated values in different rows (First normal form 1NF) http://en.wikipedia.org/wiki/First_normal_form
For that, you can implement a nice Split table valued function in SQL, by using CLR http://bi-tch.blogspot.com/2007/10/sql-clr-net-function-split.html or using plain SQL.
Then you can query the normalized output by using
cross apply
If you know the ID's rather than the strings, use this approach:
Just make sure that myarrayorcommadelimitedarray is not put in string quotes.
works if you want A OR B, but not AND.