如何将参数传递给表值函数

时间:2008-12-03 00:14:42

标签: sql-server sql-server-2005 user-defined-functions

我想做点什么

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

3 个答案:

答案 0 :(得分:37)

您需要使用 CROSS APPLY 来实现此目标

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

答案 1 :(得分:4)

以下适用于AdventureWorks数据库:

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)

修改

根据Kristof的专业知识,如果您尝试获取多个值,我已更新此示例:

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

答案 2 :(得分:0)

对我来说这看起来不错,除了你应该总是在你的函数前面加上他们的模式(通常是dbo)。所以查询应该是:

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