Question about subqueries

  • I have written a fairly complex query but I got the last part and it fails with the old "Msg 4104, Level 16, State 1, Line 3

    The multi-part identifier "..." could not be bound."

    Basically I have an outer query that joins to a subquery. That subquery has another subquery in it's WHERE clause.

    First I wrote the subquery and I hard coded in the value I want it to use from the outer most query:

    SELECT...

    FROM...

    WHERE ... = (

    SELECT MAX(...)...

    FROM...

    )

    I successfully reference the alias of the FROM table in the outer query here in the subquery and it works fine.

    Next I wrote the outermost query that I want to wrap around what I wrote above.

    SELECT...

    FROM...

    JOIN (

    SELECT...

    FROM...

    WHERE ... = (

    SELECT MAX(...)...

    FROM...

    WHERE..

    )

    )

    Unfortunately this time, when I reference the alias of the table in the outermost FROM clause, it fails. Why?

  • I guess if I had to guess, it's that the WHERE clause is applied after everything else. So the outer query has context in a subquery referenced in a WHERE clause but not in a JOIN...anyone else know what the limitations of outer query context in a subquery are? Thanks for your help.

  • I rewrote it so that it's only a single query with just the subquery in the WHERE clause. Damn thing took me all day to write with triple nested case statements and all kinds of crap. Fun fun!

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply