How to pass parameters to Table Valued Function

寵の児 提交于 2019-12-20 16:48:07

问题


I want to do something like

select * from tvfHello(@param) where @param in (Select ID from Users)

回答1:


You need to use CROSS APPLY to achieve this

select 
    f.* 
from 
    users u
    cross apply dbo.tvfHello(u.ID) f



回答2:


The following works in the AdventureWorks database:

CREATE FUNCTION dbo.EmployeeByID(@employeeID int)
RETURNS TABLE
AS RETURN
(
    SELECT * FROM HumanResources.Employee WHERE EmployeeID = @employeeID
)
GO


DECLARE @employeeId int

set @employeeId=10

select * from 
EmployeeById(@employeeId) 
WHERE @EmployeeId in (SELECT EmployeeId FROM HumanResources.Employee)

EDIT

Based on Kristof expertise I have updated this sample if your trying to get multiple values you could for example do:

select * 
from HumanResources.Employee e
CROSS APPLY  EmployeeById(e.EmployeeId)
WHERE e.EmployeeId in (5,6,7,8)



回答3:


That looks ok to me, except that you should always prefix your functions with their schema (usually dbo). So the query should be:

SELECT * FROM dbo.tvfHello(@param) WHERE @param IN (SELECT ID FROM Users)


来源:https://stackoverflow.com/questions/335886/how-to-pass-parameters-to-table-valued-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!