-- The 3rd query uses an incorrect column name in a sub-query and succeeds but rows are incorrectly qualified. This is very DANGEROUS!!!-- The issue exists is in 2008 R2, 2012 and 2014 and is "By Design"set nocount ongoif object_id('tempdb.dbo.#t1') IS NOT NULL drop table #t1if object_id('tempdb.dbo.#t2') IS NOT NULL drop table #t2GOcreate table #t1 (c1 int)insert into #t1 values (1)create table #t2 (c2 int)insert into #t2 values (2)select * from #t1select * from #t2GOselect count(*) as [Valid Join] from #t1 t1 inner join #t2 t2 on t1.c1 = t2.c2 -- corrected column name - no rows returned - GOODgoselect count(*) as [Valid Inner Query] from #t1 where c1 in (select c2 from #t2) -- corrected column name - no rows returned - GOODgoselect count(*) as [Invalid Column Name in Inner Query Works instead of failing and returns an incorrect count of 1 instead of 0] from #t1 where c1 in (select c1 from #t2) -- invalid column name c1 - WORKS and returns all rows which is incorrect - BAD !!!goselect count(*) as [Invalid Column Name in Join Fails] from #t1 t1 inner join #t2 t2 on t1.c1 = t2.c1 -- invalid column name c1 - FAILS - GOODgoThis was addressed by Microsoft as "By Design" in 2010 as per :https://connect.microsoft.com/sqlserver/feedback/details/542289/subquery-with-error-does-not-cause-outer-select-to-failThis succeeds when the invalid column name is a valid column name in the outer query. So in this situation the sub-query would fail when run by itself but succeed with an incorrectly applied filter when run as a sub-query. as Per KB article https://support.microsoft.com/en-ca/kb/298674The danger here is that if a SQL Server user runs DML in a production database with such a sub-query which then the results are likely not the expected results with potentially unintended actions applied against the data. Wondering how many SQL Server users have had incorrectly applied DML or incorrect query results and don't even know it....?
↧