Hi guys
In SQL Server 2008 I would like to create a stored procedure to select specific products, passing their IDs as argument.
But I intend to bring as result a range of products.
This range must have the informed productIds argument value (for example: 1 and 8 and 29 - that means, the range MUST have productId 1 and productId 8 and productId 29).
The unwanted ranges (those like productId 1 and productId 8, or productId 1 and productId 29, or productId 8 and productId 29) won't be shown as result.
How can I filter those unwanted ranges from my query result?
CREATE PROCEDURE [dbo].[ListProduct]
(
@categoryId
@productIds VARCHAR(4000) --Suppose we want to bring ONLY productIds 1 AND 8 AND 29
)
AS
BEGIN
SELECT
category_id,
product_id,
product_name,
FROM Product
WHERE category_id = @category_id
AND productId = --... is it better to use a function? a cursor?
END
If we have
CategoryId 1
ProductId 2
ProductId 8
ProductId 20
ProductId 29
CategoryId 2
ProductId 1
ProductId 3
ProductId 20
ProductId 29
CategoryId 3
ProductId 1
ProductId 8
ProductId 20
ProductId 29
The result would be
CategoryId 1 | ProductId 1
CategoryId 1 | ProductId 8
CategoryId 1 | ProductId 29
CategoryId 3 | ProductId 1
CategoryId 3 | ProductId 8
CategoryId 3 | ProductId 29
Here is what I've got so far:
CREATE TABLE #mylist(product_id int NOT NULL PRIMARY KEY)
INSERT #mylist
SELECT Value FROM dbo.fn_split('1,8,29',',')
SELECT category_id,product_id
FROM Product
WHERE product_id IN (SELECT product_id FROM #mylist)
But, when there's a product id missing like 8, this query is showing:
CategoryId 1 | ProductId 1
CategoryId 1 | ProductId 8
CategoryId 1 | ProductId 29
CategoryId 2 | ProductId 1 --category2 should not be displayed,
CategoryId 2 | ProductId 29 -- because product id 8 is missing....
CategoryId 3 | ProductId 1
CategoryId 3 | ProductId 8
CategoryId 3 | ProductId 29