I am quite new at database programming and I am having trouble doing searches in my database. I have a table with a column named Required_Items, it is just a list of required items separated by ‘;’. I can’t get the server to return the rows when querying :
'SELECT * FROM The_Table WHERE Required_Items LIKE '%item1%' '
It seems that the database can’t find that item in the column. The problem is that I want to be able to return rows that contain ALL the items. I would try something like:
'SELECT *
FROM The_Table
WHERE Requiered_Items LIKE '%item1%' AND
Requiered_Items LIKE '%item2%' AND
Requiered_Items LIKE '%item3%' AND//etc...
How can I do that knowing that there will be a variable number of these “items” to test ?
When I have problems like this it invariably turns out to be that my comparison strings simply don’t match. (That’s not to say they don’t look like they match.) Common reasons are spelling mistakes, upper vs lower case issues, characters (particularly spaces) aren’t what they appear to be. Do you have spaces in any of your ‘like’ comparisons?
How did you get the data into the database? Did you copy it from Word or Excel and paste it into the SQL query builder, or somethng of that nature? That can cause problems if you’re not careful.
And of course you know that ALL of your ‘like’ comparisons must match in order to get data…?
Here’s an example of what may be happening:
If the ‘Required Items’ field = ‘Bat, Ball, Glove, Cap, Helmet, Water Battle’
then these will both fail:
(Because ‘Water Bottle’ is spelled incorrectly in the database)
You can troubleshoot for this kind of problem by having one item at a time in your where clause until you find the one that fails.
Regarding a variable number of items, using the data the way you have it set up (all items in one csv field) your code might be cleanest if you used dynamic sql. That’s where you build a query in a string vaiable and execute the variable. Search for “Dynamic SQL”.
All that said, the preferred method of storing this kind of data in a relational database is to create maintainable relationships between entities. Your data would be much friendlier if you broke the items out into a structure like this:
This structure would make handling unknown numbers of items very easy to deal with.
If you can’t solve this, post actual code and actual data if you can.
Scott