我编写了一个View的代码,它需要调用一个用户定义的函数,该函数返回一个表来与它连接。这里的问题是直接传递这个函数需要的参数。
以下是我的观点代码:
select
GG.Gid,
GG.StockType StockType,
COALESCE(STC.Contract, 0) ContractId,
COALESCE(C.[$Refex], null) ContractRefex,
ST.[$Refex] StockTypeRefex
from
(
select
G.Gid,
coalesce(max(G.GEStockType), max(G.EAStockType)) StockType--,
--case when coalesce(G.GEStockType, G.EAStockType) is null then null else coalesce(G.GEStartDate, G.EAStartDate) end StartDate
from
(
select
G.Gid, SI.StockType EAStockType, SI.[Date] EAStartDate, null GEStockType, null GEStartDate
from Goods G
inner join SiteIn SI on G.SiteIn=SI.[$Id]
union
select G.Gid, null EAStockType, null EAStartDate, GE.StockType, GE.EventOn
from
(
Select
GE.Gid, max(GE.EventOn) GEStartDate
from GoodsEvent GE
where GE.IsDeleted=0 and GE.[Type]='ST' and GE.EventOn < GETDATE()
group by Gid
) G
inner join GoodsEvent GE on GE.Gid=G.Gid
and G.GEStartDate=GE.EventOn
and GE.[Type]='ST'
) G
group by G.Gid
) GG
left outer join StockType ST on ST.[$Id]=GG.StockType
inner join (SELECT * FROM [dbo].StockTypeContractGetClosestStartDate(ST.[$Id]))
STC on GG.StockType = STC.[Parent]
inner join Contract C On STC.Contract = C.[$Id]
这是我的功能代码:
CREATE FUNCTION StockTypeContractGetClosestStartDate
(
@ParentId int
)
RETURNS @StockTypeContract TABLE
(
[StartDate] [DateTime] null,
[Parent] [int] not null,
[Contract] [int] null
)
AS
BEGIN
INSERT @StockTypeContract
SELECT TOP 1 STC.StartDate , STC.[$ParentId] , STC.Contract
from StockTypeContract STC
where STC.[$ParentId] = @ParentId AND STC.StartDate <= GETDATE()
order by STC.StartDate desc
RETURN
END
尝试将ST。[$ Id]传递给我的函数时出现错误,错误是“多部分标识符ST。$ Id无法绑定”。
有没有解决方法呢?
答案 0 :(得分:4)
您实际需要CROSS or OUTER APPLY。并from SO too
....
left outer join StockType ST on ST.[$Id]=GG.StockType
CROSS APPLY
[dbo].StockTypeContractGetClosestStartDate(ST.[$Id])
...
(我在这里简化括号BTW,可能是错误的)
您的问题是“从StockTypeContractGetClosestStartDate获取结果集每 ST。[$ Id]
答案 1 :(得分:0)
如果我是正确的,你只在函数的返回表中插入一条记录,如果是这种情况,那么你可以将函数重建为标量函数,这只返回一个值,并应该解决多部分问题。
目前你正试图加入一个可能的“多值id”。
请参阅http://technet.microsoft.com/en-us/library/ms186755.aspx了解标量函数