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

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) 

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)