用户定义函数 SQL 2008

User Defined function SQL 2008

我正在尝试创建一个 returns 一个 INT 值的计算列,我已经创建了一个函数并且需要将 ndx 编号传递给该函数并且在子查询中返回多个值时遇到问题. 如何将 ndx 数字传递给函数,我假设计算列查看同一行中的值!?

    Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

函数

CREATE FUNCTION dbo.Nat_Weight(@me38_cycle_data_ndx INT)
RETURNS INT
AS 
BEGIN
DECLARE @nat_weight INT =0;
DECLARE @mattype1 INT;
DECLARE @mattype2 INT;
DECLARE @mattype3 INT;
--DECLARE @me38_cycle_data_ndx INT;
-- get material type, need only hoppers 1-3, hopper 4,5,6 material type will never = 2
SET @mattype1 = (SELECT typehopper_01 FROM mm_Cycle_Data);
SET @mattype2 = (SELECT typehopper_02 FROM mm_Cycle_Data );
SET @mattype3 = (SELECT typehopper_03 FROM mm_Cycle_Data );
-- if material type=2 then add to @nat_weight ,  
IF @mattype1 = 2
    set @nat_weight = (SELECT cyclehopper_01 FROM mm_Cycle_Data WHERE me38_cycle_data_ndx=@me38_cycle_data_ndx );
IF @mattype2 = 2
    set @nat_weight =@nat_weight+ (SELECT cyclehopper_02 FROM mm_Cycle_Data WHERE me38_cycle_data_ndx=@me38_cycle_data_ndx );
IF @mattype3 = 2
    set @nat_weight =@nat_weight+ (SELECT cyclehopper_03 FROM mm_Cycle_Data WHERE me38_cycle_data_ndx=@me38_cycle_data_ndx )
RETURN @nat_weight
END 

我认为 SQL 服务器抱怨这些行:

SET @mattype1 = (SELECT typehopper_01 FROM mm_Cycle_Data);
SET @mattype2 = (SELECT typehopper_02 FROM mm_Cycle_Data);
SET @mattype3 = (SELECT typehopper_03 FROM mm_Cycle_Data);

听起来 mm_Cycle_Data 中有多行。如果使用子查询赋值,子查询只能return 1行。

您需要将 WHERE 子句添加到这些子查询到 return 单行。此外,您可以像这样组合它们:

SELECT @mattype1 = typehopper_01,
       @mattype2 = typehopper_02,
       @mattype3 = typehopper_03
FROM mm_Cycle_Data
WHERE me38_cycle_data_ndx=@me38_cycle_data_ndx