用户定义的函数SQL 2008

时间:2015-10-28 18:06:20

标签: sql-server-2005 user-defined-functions

我正在尝试创建一个返回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 

1 个答案:

答案 0 :(得分:2)

我认为SQL Server抱怨这些行:

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中有多行。如果使用子查询分配值,则子查询只能返回1行。

您需要为这些子查询添加WHERE子句以返回单行。此外,您可以将它们组合在一起:

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