如何将用户定义的表类型传递给内联函数

How to pass user-defined table type to inline function(如何将用户定义的表类型传递给内联函数)
本文介绍了如何将用户定义的表类型传递给内联函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一些复杂的函数,我想在多个查询中使用它们.它获取一些值列表并返回聚合值.

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
)

我想在查询中使用它:

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

我知道我可以使用游标或将值作为 XML 传递,但我认为这种方式比内联函数和表变量慢.

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?

推荐答案

首先你应该使用 Inline 函数中使用的 table type(Number) 创建一个 table 变量.

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

将需要的行插入表变量并传递表变量 o 内联函数

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

你需要做这样的事情

declare @Numbers Numbers

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

select * from Mean(@Numbers)

更新:根据您的评论

创建一个新的表格类型.

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

Alter 函数

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) 

调用函数

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) 

这篇关于如何将用户定义的表类型传递给内联函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Query with t(n) and multiple cross joins(使用 t(n) 和多个交叉连接进行查询)
Unpacking a binary string with TSQL(使用 TSQL 解包二进制字符串)
Max rows in SQL table where PK is INT 32 when seed starts at max negative value?(当种子以最大负值开始时,SQL 表中的最大行数其中 PK 为 INT 32?)
Inner Join and Group By in SQL with out an aggregate function.(SQL 中的内部连接和分组依据,没有聚合函数.)
Add a default constraint to an existing field with values(向具有值的现有字段添加默认约束)
SQL remove from running total(SQL 从运行总数中删除)