我正在创建一个函数,所以我可以获取select语句的结果并将它们放在我们数据库的视图中。我的SELECT语句在运行时返回一个结果,但是当我将它放入创建函数时,我得到错误:
Only one expression can be specified in the select list when the
subquery is not introduced with EXISTS.
我仍然是新人并且正在学习,并且会感谢我在做错的任何帮助。
CREATE FUNCTION CXi_Application
@Application nvarchar(255), @Wave nvarchar(255)
RETURNS int
AS
BEGIN
DECLARE @Return int
SET @Return =
(SELECT @Application, (
(sum(CASE WHEN overall_score IN (1) THEN 1 ELSE 0 END) + sum(CASE WHEN effective_score IN (1) THEN 1 ELSE 0 END) + sum(CASE WHEN easeuse_score IN (1) THEN 1 ELSE 0 END)) +
(sum(CASE WHEN overall_score IN (2) THEN 2 ELSE 0 END) + sum(CASE WHEN effective_score IN (2) THEN 2 ELSE 0 END) + sum(CASE WHEN easeuse_score IN (2) THEN 2 ELSE 0 END)) +
(sum(CASE WHEN overall_score IN (3) THEN 3 ELSE 0 END) + sum(CASE WHEN effective_score IN (3) THEN 3 ELSE 0 END) + sum(CASE WHEN easeuse_score IN (3) THEN 3 ELSE 0 END)) +
(sum(CASE WHEN overall_score IN (4) THEN 4 ELSE 0 END) + sum(CASE WHEN effective_score IN (4) THEN 4 ELSE 0 END) + sum(CASE WHEN easeuse_score IN (4) THEN 4 ELSE 0 END)) +
(sum(CASE WHEN overall_score IN (5) THEN 5 ELSE 0 END) + sum(CASE WHEN effective_score IN (5) THEN 5 ELSE 0 END) + sum(CASE WHEN easeuse_score IN (5) THEN 5 ELSE 0 END)))/
(count(overall_score) + count(effective_score) + count(easeuse_score) * 1.00 )
FROM FY14_DataMerge
WHERE [Status] = 'Completed' AND [Application] = @Application AND [Wave] = @Wave);
-- Return the result of the function
RETURN @Return
END
GO
答案 0 :(得分:7)
您已在DDL中指定您希望该函数返回INT
RETURNS int
但是,您的结果集包含@Application
和计算本身。基本上,您已声明您正在创建标量值函数,但您的代码正在尝试返回表值结果。首先,您需要确定您想要实际执行的操作。
如果你要返回一个结果(通常在调用语句的SELECT
部分中找到),那么你很可能正在寻找一个标量值函数,你需要删除{{1}从函数DDL中的@Application
语句调用。
如果您确实想要从函数返回的值,那么您将需要一个表值函数。此外,这是一个非常简单的查询,因此您可以将其设为具有definite performance benefits的内联TVF,但我不确定它们在您的情况下会有多清楚。
以下是制作内联TVF的样子:
SELECT
但是,如果5是每个数据点的最大值,那么为什么不重构为:
CREATE FUNCTION CXi_Application
@Application nvarchar(255), @Wave nvarchar(255)
RETURNS TABLE
AS
RETURN SELECT @Application as [Application], (
(sum(CASE overall_score WHEN 1 THEN 1 ELSE 0 END)
+ sum(CASE effective_score WHEN 1 THEN 1 ELSE 0 END)
+ sum(CASE easeuse_score WHEN 1 THEN 1 ELSE 0 END))
+
(sum(CASE overall_score WHEN 2 THEN 2 ELSE 0 END)
+ sum(CASE effective_score WHEN 2 THEN 2 ELSE 0 END)
+ sum(CASE easeuse_score WHEN 2 THEN 2 ELSE 0 END))
+
(sum(CASE overall_score WHEN 3 THEN 3 ELSE 0 END)
+ sum(CASE effective_score WHEN 3 THEN 3 ELSE 0 END)
+ sum(CASE easeuse_score WHEN 3 THEN 3 ELSE 0 END))
+
(sum(CASE overall_score WHEN 4 THEN 4 ELSE 0 END)
+ sum(CASE effective_score WHEN 4 THEN 4 ELSE 0 END)
+ sum(CASE easeuse_score WHEN 4 THEN 4 ELSE 0 END))
+
(sum(CASE overall_score WHEN 5 THEN 5 ELSE 0 END)
+ sum(CASE effective_score WHEN 5 THEN 5 ELSE 0 END)
+ sum(CASE easeuse_score WHEN 5 THEN 5 ELSE 0 END)))
/
(count(overall_score) + count(effective_score)
+ count(easeuse_score) * 1.00 ) as CalcMetric
FROM FY14_DataMerge
WHERE [Status] = 'Completed' AND [Application] = @Application AND [Wave] = @Wave;
GO