Wednesday, 28 February 2018

Microsoft SQL Cross Apply and Outer Apply Statements

Microsoft SQL Cross Apply and Outer Apply Statements
-- The apply statements are used to join tables to functions
-- Cross Apply is an inner join between tables and functions
-- Outer Apply is a left outer join between tables and functions

--Create Function
create function fn_top_5_fx_majors(@product varchar(50))
returns table
return
(SELECT TOP 5 [Product]
      ,[Low]
      ,[High]
      ,[Close]
      ,[Previous]
      ,[Direction]
      ,[Date]
  FROM [test].[dbo].[options on fx majorsii]
  where @product=[Product]
  order by 1);


  --view function rows
select * from fn_top_5_fx_majors('aud/usd');

-- create cross apply inner join
select *
from [test].[dbo].[options on fx majors] as fx
cross apply fn_top_5_fx_majors(fx.Product);



--create outer apply left outer join
select *
from [test].[dbo].[options on fx majors] as fx2
outer apply fn_top_5_fx_majors(fx2.Product);

Inline image 1

No comments:

Post a Comment