Link to home
Start Free TrialLog in
Avatar of GreatSolutions
GreatSolutionsFlag for Israel

asked on

Select from comma delimited list previously saved in a char field

I have a table with, among other fields, a varchar field named "Countries" that contains a comma delimited lists of country codes ( ie "28,76,78,98")
How can i select for instance all records where the id 78 is in that Countries list?

Thanks
Jaime
Avatar of Simon
Simon
Flag of United Kingdom of Great Britain and Northern Ireland image

where countries like '%[^0-9]78[^0-9]%'
Avatar of GreatSolutions

ASKER

Hi
It doesn't work
The worst possiible way to use SQL fields is to try storing compound data in them.  One field should contain one value and nothing more.  
Storing complex data like that slows your system down by massive amounts.  A linked table with two fields in it would have been your answer.

NewTable:CountryLinks
int ReferencID
int CountryCode

The referenceID is the key of the record that originally held your "Countries" field and CountryCode is each of the individual elements from your Counries field.

So assuming that your example above where you had  country codes ( "28,76,78,98") in a row with an ID field value of 129, you would have entries of....
ReferenceID  CountryCode
129                  28
129                  76
129                  78
129                  98

Now you can easily select anything in a normal, indexed, SELECT statement joining the two tables.
I understand Neil but in this case i must use the field with the concat values in it...
ASKER CERTIFIED SOLUTION
Avatar of Neil Russell
Neil Russell
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Changed the double quotes to single, and also added "or countries='78' for the case where there is only one country. Tested and it works correctly. I don't mind about speed, this is a table with a few hundred records at the most

Many thanks