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

时间:2022-04-22 11:10:45

I want to do something like

我想做点什么

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

3 个解决方案

#1


32  

You need to use CROSS APPLY to achieve this

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

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

#2


3  

The following works in the AdventureWorks database:

以下适用于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)

EDIT

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

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

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

#3


0  

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

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

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

#1


32  

You need to use CROSS APPLY to achieve this

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

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

#2


3  

The following works in the AdventureWorks database:

以下适用于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)

EDIT

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

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

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

#3


0  

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

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

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