问题描述
我有一些复杂的函数,我想在多个查询中使用它们.它获取一些值列表并返回聚合值.
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)
这篇关于如何将用户定义的表类型传递给内联函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!