2013-04-29 58 views
0

我有兩個功能:如何加入這兩個函數結果集?

fn_get_AB_associations(Date from, Date to, Int AentityId) 

獲得的結果與這些字段設置:

datefrom | AentityId | BentityId 

而且

fn_get_BC_associations(Date from, Date to, Int BentityId) 

獲得的結果與這些字段設置:

datefrom | BentityId | CentityId 

我需要選擇與日期範圍內的實體關聯的所有C實體。

我試圖做這樣的事情:

select DISTINCT T1.BentityId from dbo.fn_get_AB_associations('2013-04-01', '2013-04-15', 'PF') T1 
INNER JOIN fn_get_BC_associations('2013-04-01', '2013-04-15', T1.BentityId) T2 
ON T1.BentityId = T2.BentityId 

但我顯然得到這個錯誤:The multi-part identifier "T1.BentityId" could not be bound.

所以...有沒有辦法參加這兩個結果集或我要cicle第一個函數的結果併爲每個函數調用第二個函數?

回答

2

嘗試這一個 -

DECLARE 
     @DateStart DATETIME 
    , @DateEnd DATETIME 

SELECT  
     @DateStart = '2013-04-01' 
    , @DateEnd = '2013-04-15' 

SELECT DISTINCT 
     t1.DateFrom 
    , t1.AentityId 
    , t1.BentityId 
    , t2.* 
FROM dbo.fn_get_AB_associations(@DateStart, @DateEnd, 'PF') t1 
OUTER APPLY (
    SELECT 
      t2.DateFrom 
     , t2.CentityId 
    FROM dbo.fn_get_BC_associations(@DateStart, @DateEnd, t1.BentityId) t2 
    WHERE t1.BentityId = t2.BentityId 
) t2 
+0

完美!非常感謝你! – davioooh 2013-04-29 09:54:31

+0

不客氣@davioooh。 – Devart 2013-04-29 09:56:07