如何加入这两个函数结果集?

时间:2013-04-29 09:24:01

标签: sql-server tsql function sql-server-2005 join

我有两个功能:

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

我需要在日期范围内选择与A实体关联的所有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并为每个结果调用第二个函数?

1 个答案:

答案 0 :(得分: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