How to pass user-defined table type to inline function

谁说胖子不能爱 提交于 2020-01-07 04:36:10

问题


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) 


来源:https://stackoverflow.com/questions/39471816/how-to-pass-user-defined-table-type-to-inline-function

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