Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters to Table Valued Function

I want to do something like

select * from tvfHello(@param) where @param in (Select ID from Users) 
like image 289
R.D Avatar asked Dec 03 '08 00:12

R.D


People also ask

How do you declare a table-valued parameter?

Table-valued parameters are declared by using user-defined table types. You can use table-valued parameters to send multiple rows of data to a Transact-SQL statement or a routine, such as a stored procedure or function, without creating a temporary table or many parameters.

Can we pass parameter to function in SQL?

We can also pass dates as parameters in the SQL Server functions. In this section, we will create a function that will take a particular date as the input parameter.


2 Answers

You need to use CROSS APPLY to achieve this

select      f.*  from      users u     cross apply dbo.tvfHello(u.ID) f 
like image 111
kristof Avatar answered Sep 18 '22 15:09

kristof


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) 
like image 45
JoshBerke Avatar answered Sep 16 '22 15:09

JoshBerke