SQL and the like

Dave Ballantyne's blog. Freelance SQL Server database designer and developer at Clear Sky SQL

Cross Apply Ambiguity

Cross apply (and outer apply)  are a very welcome addition to the TSQL language.  However, today after a few hours of head scratching, I have found an simple issue which could cause big big problems.

What would you expect from this statement ?

select * 
  from sys.objects b    
  join sys.objects a
    on a.object_id = object_id

No prizes for guessing SQL server errors with “Ambiguous column name 'object_id'”.

What would you expect from this statement ?

Select * 
  from sys.objects a
  cross apply( Select * 
                from sys.objects b where b.object_id = object_id) as c

Surprisingly, perhaps, the result is a cross join of sys.objects.  Well, what happened there ?

If you look at the apply statement, within the where clause, only one of the conditions is qualified with a table name.  This meant that is has be interpreted as “b.object_id = b.object_id” causing the cross apply to have no join the the parent sys.objects table and causing the cross join.

The fix is , obviously, simple

Select * 
  from sys.objects a
  cross apply( Select * 
                from sys.objects b where b.object_id = a.object_id) as c

So why no “Ambiguous column name ” error ?  I’ve raised a connect item on this issue here.

Comments

brad_schulz said:

Hi Dave...

This behavior has been around since the beginning and it will never be changed.

Subqueries (and, by extension, derived tables and CROSS APPLY queries) are in their own localized universe... even when they are CORRELATED subqueries.  When SQL sees the Object_ID column reference, the only place it goes to resolve that is within the subquery itself... the subquery is not aware of the "outside world" at all, even though you yourself might correlate it by introducing a column that makes a reference to a table alias outside, and you MUST use that table alias to tell it where that "outside" column is... other than that, any un-aliased column will always be assumed to be from a table within the subquery itself.

So there really is no ambiguous name at all.

--Brad

# March 26, 2010 4:48 PM

Twitter Trackbacks for Cross Apply Ambiguity - SQL and the like [sqlblogcasts.com] on Topsy.com said:

Pingback from  Twitter Trackbacks for                 Cross Apply Ambiguity - SQL and the like         [sqlblogcasts.com]        on Topsy.com

# March 27, 2010 12:41 AM