I’m trying to write code to pull a list of product items from a SQL Server database an display the results on a webpage.
A requirement of the project is that a list of categories is displayed at the right hand side of the page as a list of checkboxes (all categories selected by default) and a user can uncheck categories and re-query the database to view products’s in only the categories they want.
Heres where it starts to get a bit hairy.
Each product can be assinged to multiple categories using a product categories table as below…
Product table [product_id](PK),[product_name],[product_price],[isEnabled],etc... Category table [CategoryID](PK),[CategoryName] ProductCagetory table [id](PK),[CategoryID](FK),[ProductID](FK)
I need to select a list of products that match a set of category ID’s passed to my stored procedure where the products have multiple assigned categories.
The categort id’s are passed to the proc as a comma delimited varchar i.e. ( 3,5,8,12 )
The SQL breaks this varchar value into a resultset in a temp table for processing.
How would I go aout writing this query?
This should be fairly close to what you are looking for
EDIT
As noted in the comments this will produce duplicates for those products appearing in multiple categories. To correct this then specify
DISTINCTbefore the column list. I have included all product columns in the listproduct.*as I do not know which columns you are looking for but you should probably change that to the specific columns that you want