在表值函数中使用select查询作为参数

时间:2016-02-19 15:12:27

标签: sql-server table-valued-parameters cross-apply

我有一个接受整数输入的函数,并返回一个包含下表中相关ID的表。

ID  NAME    RELATED_ID
1   a       null
2   b       null
3   c       1
4   d       1

因此,select * from fn_getrelatedids(1)返回

ID
1
3
4

我想使用动态参数作为函数的参数,即

select * from fn_getrelatedids (select e.id from entity e where e.name='a')

显然这不起作用。

我试过交叉申请:

select e.id from entity e 
cross apply 
(select f.id from fn_getrelatedids (e.id) AS fg
WHERE fg.id = e.id) AS R
WHERE e.name = 'a'

这不会返回正确的值。该函数仅返回

ID
1

我错过了一些明显的东西吗?

2 个答案:

答案 0 :(得分:2)

看看这不是你想要做的。

select fg.id 
from entity e 
cross apply dbo.fn_getrelatedids(e.id) AS fg
WHERE e.name = 'a'

编辑:添加正确的选择

答案 1 :(得分:0)

示例:

SELECT      table1.f_code, 
            table1.subsidiaryledger AS ledgerid, 
            table1.subgroupid , 
            table1.openingamt, 
            table1.ac_type, 
            0 AS debitamount, 
            0 AS creditamount, 
            closing , 
            closing_type 
FROM        ledgersubsidiaryopeningbalanace   AS table1 
** cross apply 
dbo.getsubsidaryclosingnew (table1.subsidiaryledger,table1.subgroupid,table1.openingamt,table1.ac_type,0,0) AS tv
WHERE       table1.subsidiaryledger = tv.ledgerid 
AND         table1.subgroupid = tv.subgroupid** 
AND         subsidiaryledger = 15105 
AND         f_code = 1