How to pass user-defined table type to inline func

2019-09-19 16:07发布

问题:

I have some complex function that I want to use in number of queries. It gets some list of values and return aggregate value.

For example (I simplify it, it is more complex in deed):

CREATE FUNCTION Mean(@N Numbers READONLY)
RETURNS TABLE AS RETURN (
    SELECT mean = SUM(n.value) / COUNT(*) FROM @N n
)

and I want to use it in query:

SELECT d.DepartmentName, MeanRate = m.mean
FROM Departments d
CROSS APPLY Mean(
    (
        SELECT value = e.Rate
        FROM Employees e
        WHERE e.DepatmentId = d.DepatmentId
    )
) m

But I get an error: Operand type clash: float is incompatible with Numbers

I know that I can use cursor or pass values as XML, but I think this ways are slower than inline function and table variables.

How can I pass a list of values to inline function?

回答1:

First you should create a table variable using the table type(Number) used in the Inline function.

Insert the required rows into table variable and pass the table variable o Inline function

You need to do something like this

declare @Numbers Numbers

Insert into @Numbers 
select e.Rate
From Employees  E join 
Departments d on e.DepatmentId = d.DepatmentId

select * from Mean(@Numbers)

Update : Based on your comments

Create a new table type.

CREATE TYPE Dept_number AS TABLE
(
DepatmentId  INT ,value numeric(22,6)
);

Alter the function

ALTER FUNCTION Mean(@dept_number DEPT_NUMBER readonly) 
returns TABLE 
AS 
    RETURN 
      (SELECT depatmentid, 
              mean = Sum(n.value) / Count(*) 
       FROM   @dept_number n 
       GROUP  BY depatmentid) 

Calling the function

DECLARE @dept_number DEPT_NUMBER 

INSERT INTO @dept_number 
            (depatmentid, 
             value) 
SELECT d.depatmentid, 
       e.rate 
FROM   employees E 
       JOIN departments d 
         ON e.depatmentid = d.depatmentid 

SELECT * 
FROM   Mean(@dept_number)