Pregunta

Why this does not give any records in sql server 2008?

;with pricedCategories as
(
    select * from Product.Category where CategoryID not in
    (select Parent_CategoryID from Product.Category)
)
select * from pricedCategories
¿Fue útil?

Solución

It seems that your query doesn't return values when there are NULL values in subquery inside CTE (if I replace NULL in insert (1, NULL) with let's say (1, 0) your query will work). If you want to get the categories that are not any other category's parents even with NULL values, you can do it like this:

DECLARE @Category TABLE (CategoryID INT, Parent_CategoryID INT)
INSERT @Category VALUES 
(1, NULL),
(2, 1),
(3, 1),
(4, 2)

;WITH pricedCategories AS
(
    SELECT * FROM @Category y WHERE NOT EXISTS 
    (SELECT Parent_CategoryID FROM @Category x 
     WHERE  x.Parent_CategoryID = y.CategoryID)
)
SELECT * FROM pricedCategories

It is interesting to see that the following approach works the same as the approach described in your question:

;WITH pricedCategories AS
(
    SELECT * FROM @Category y 
    WHERE  y.CategoryID <> ALL(SELECT DISTINCT Parent_CategoryID FROM @Category)
)
SELECT * FROM pricedCategories

You could change your query to use the ISNULL function to replace NULL with some numeric value that is never used as CategoryID, like this:

;WITH pricedCategories AS
(
    SELECT * FROM @Category WHERE CategoryID NOT IN
    (SELECT ISNULL(Parent_CategoryID, -1) FROM @Category)
)
SELECT * FROM pricedCategories

But then the NULL value which means "nothing" would be changed to actual value of -1 which is not true and you shouldn't use it.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top