November 10, 2008 at 1:42 pm
Hey all,
I have a stored procedure in which one of the parameters being passed to it contains an XML string in which i have a (random) number of elements. Within each of these elements i have a value attribute which contains an ID which i would like to filter my result set on. Please take a look at the following code:
Declare @XMLDoc XML;
set @XMLDoc= '<root><item value="46" /><item value="50" /></root >';
SELECT * FROM
(
SELECT DISTINCT tblProductCategory.CategoryID, tblProduct.*, tblProductFeatureValue.FeatureValueID
FROM tblProduct INNER JOIN tblProductFeatureValue ON tblProduct.ProductID = tblProductFeatureValue.ProductID INNER JOIN
tblProductCategory ON tblProduct.ProductID = tblProductCategory.ProductID
WHERE IsDiscontinued <> 'True'
AND tblProductCategory.CategoryID = 1
) AS Q1 WHERE FeatureValueID IN
(
select x.item.value('@value','int') from @XMLDoc.nodes('/root/item') as x(item)
)
Now the above code works ok, it will return me all products who have a FeatureValueID of 46 OR 50.
What i need is a method which will return all products who have a FeatureValueID of 46 AND 50.
Any ideas would be most welcome.
Thanks in advance.
November 11, 2008 at 3:09 am
You will have to do a COUNT. Something like:
SELECT DISTINCT
    C.CategoryID
    ,P.*
    ,F.FeatureValueID
FROM tblProduct P
    JOIN tblProductFeatureValue F
        ON P.ProductID = F.ProductID
    JOIN tblProductCategory C
        ON P.ProductID = C.ProductID
    JOIN
    (
        SELECT F1.ProductID
        FROM tblProductFeatureValue F1
        WHERE F1.FeatureValueID IN
        (
            SELECT X1.item.value('@value','int')
            FROM @XMLDoc.nodes('/root/item') X1(Item)
        )
        GROUP BY F1.ProductID
        HAVING COUNT(*) =
        (
            SELECT COUNT(X2.item.value('@value','int'))
            FROM @XMLDoc.nodes('/root/item') X2(Item)
        )
    ) D
        ON P.ProductID = D.ProductID
WHERE IsDiscontinued <> 'True'
    AND C.CategoryID = 1
ps You may want to experiment with passing a delimited string and using a split string function (plenty on this site) as the overhead for XML can be quite high.
Viewing 2 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply