第五章 表表达式(2)

use TSQLFundamentals2008;

declare @name as nvarchar(max) = 'Anders Fan'

--5.4 内联表值函数
--除了支持输入参数之外,内联表值函数在其他方面与视图类似
if OBJECT_ID('dbo.fn_getcustorders') is not null
drop function dbo.FN_GetCustOrders;
go

create function dbo.FN_GetCustOrders
(@cid as int) returns table
as 
return 
select * from sales.orders
where custid=@cid;
go

select orderid, custid
from dbo.FN_GetCustOrders(1);

--5.5 APPLY运算符
--与联接不同的是Cross Apply的右表表达式可能代表不同的数据行集合,
--可以在右边使用一个派生表,在派生表的查询中去引用左表列;也可以是
--内联表值函数,把左表中的列作为输入参数进行传递
--返回每个客户最新的三个订单
select c.custid, o.orderid, o.orderdate
from Sales.Customers as c
cross apply
(select top(3) * from Sales.Orders 
where c.custid = custid 
order by orderdate desc) as o

--Outer Apply运算符增加了另一个逻辑处理阶段;标识出让右表表达式返回
--空集的左表中的数据行,并把这些行作为外部行添加到结果集中,来自右表
--表达式的列用null作为占位符.从某种意义上讲,这个处理类似于做外联接
--中增加外部行的一步.
select c.custid, o.orderid, o.orderdate
from Sales.Customers as c
outer apply
(select top(3) * from Sales.Orders
where c.custid = custid
order by orderdate desc) as o

if OBJECT_ID('dbo.fn_TopOrders') is not null
drop function dbo.FN_TopOrders;
go

create function dbo.FN_TopOrders
(@cid as int, @tnum as int)
returns table
as return
(select top(@tnum) * from Sales.Orders
where custid=@cid
order by orderdate desc);

select c.custid, o.orderid, o.orderdate
from Sales.Customers as c
outer apply dbo.FN_TopOrders(c.custid, 3) as o

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值