0

I have a nested SQL select statement where the sub select relies on a value from the parent select. However, the query fails due to a null value (I think). How do I get the query to ignore the sub select statement each time it comes across a null value?

Here's my query:

SELECT ID, Hierarchy, Name, Hierarchy.GetLevel() AS Level, Hierarchy.GetAncestor(1) AS ParentHierarchy,
        (SELECT ID
         FROM  SpecProducts
         WHERE (Hierarchy = ParentHierarchy)) AS ParentHierarchy

FROM          SpecProducts AS SpecProducts_1
WHERE        (EnableDisable IS NULL)
ORDER BY Hierarchy

Here is my error message:

Invalid column name 'ParentHierarchy'

******************** EDIT: 24/04/2012 - 14:50 *****************

Thanks for pointing out the error. Unfortunately I still get the same problem.

Here's the updated query:

SELECT ID, Hierarchy, Name, Hierarchy.GetLevel() AS Level, Hierarchy.GetAncestor(1) AS ParentHierarchy,
                         (SELECT  ID
                          FROM    SpecProducts
                          WHERE  (Hierarchy = ParentHierarchy)) AS ParentID
FROM    SpecProducts AS SpecProducts_1
WHERE   (EnableDisable IS NULL)
ORDER BY Hierarchy

Error Message: Invalid Column Name 'ParentHierarchy'

Is the problem because the ParentHierarchy value can be NULL?

** EDIT ************

Ok this works:

SELECT   ID, Hierarchy, Name, Hierarchy.GetLevel() AS Level, Hierarchy.GetAncestor(1) AS ParentHierarchy,
         (SELECT   ID AS IDd
          FROM     SpecProducts
          WHERE    (Hierarchy = SpecProducts_1.Hierarchy.GetAncestor(1))) AS ParentID
FROM            SpecProducts AS SpecProducts_1
WHERE        (EnableDisable IS NULL)
ORDER BY Hierarchy
4

4 回答 4

1

You have two fields named ParentHierarchy. You need to change the second field to be named something else. Also, you are trying to reference an alias inside the nested SELECT statement. Try referencing the GetAncestor(1) method instead.

于 2012-04-24T12:04:39.460 回答
1

use use the name ParentHierarchy twice. try

SELECT ID, ..., Hierarchy.GetAncestor(1) AS ParentHierarchy,
    (SELECT ID
     FROM  SpecProducts
     WHERE (Hierarchy = ParentHierarchy)) AS ParentHierarchyID ...
于 2012-04-24T12:04:40.573 回答
0

It is because you are trying to give the name ParentHierarchy to 2 different columns in your main SELECT statement:

Hierarchy.GetAncestor(1) AS ParentHierarchy

and

(SELECT ID ...) AS ParentHierarchy
于 2012-04-24T12:05:36.080 回答
0
SELECT ID, Hierarchy, Name, Hierarchy.GetLevel() AS Level, Hierarchy.GetAncestor(1) AS ParentHierarchy,
        (SELECT ID
         FROM  SpecProducts as sp2
         WHERE (sp2.Hierarchy = SpecProducts_1.Hierarchy)) AS ParentHierarchy2

FROM          SpecProducts AS SpecProducts_1
WHERE        (EnableDisable IS NULL)
ORDER BY Hierarchy
于 2012-04-24T12:23:47.600 回答