SQL Server Select TOP 0 and OUTER APPLY

pwuypxnk  于 2023-03-17  发布在  其他
关注(0)|答案(1)|浏览(128)

I'm facing a piece of code that seems very difficult for me to comprehend tho I have a brief understanding how both Select TOP 0 and Outer APPLY work separetely. What does this code do? Thanks is advance!

select * from taxex t1
   outer apply 
         (select top 0 id, b_date, total_sum from loans t2 where t1.id = t2.id 
                                               and t1.i_date >= t2.b_date) ```
6rqinv9w

6rqinv9w1#

The only possibly useful action of the outer apply in question is the null values in columns generated by the outer apply are casted to the type of respective columns of the loan table. Compare:

The query below will fail with
Msg 241 Level 16 State 1 Line 1 Conversion failed when converting date and/or time from character string.

select  t1.*, t2.*
from (
   select 1 a, 2 b
) t1
outer apply (
  select top 0 cast('2002-01-01' as date) d
) t2

union all 
select 3, 4, 'abc';

While the next one is ok

select  t1.*, null d
from (
   select 1 a, 2 b
) t1

union all 

select 3, 4, 'abc'

相关问题