用户定义的函数返回Scalar-Valued中的语句

时间:2015-12-10 08:34:47

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

我有一个包含以下列的表:

CREATE FUNCTION ReturnMelli ( @Melicode CHAR(10) )
RETURNS INT
AS 
    BEGIN
        DECLARE @RESULT BIT
        SET @RESULT = ( SELECT  Isactive
                        FROM    TblPerson
                        WHERE   MeliCode = @Melicode
                      )
        DECLARE @R INT
        SET @R = ( SELECT   [Count]
                   FROM     TblPerson
                   WHERE    MeliCode = @Melicode
                 )
        IF ( @RESULT = 1 ) 
            BEGIN
                RETURN @R
            END
        ELSE 
            BEGIN
                RETURN 0
            END

    END

现在我想编写一个UDF,它将Melicode作为输入参数,如果IsActive = 1,则UDF返回count的值,否则UDF必须返回0。 我写下以下函数

Msg 455, Level 16, State 2, Procedure ReturnMelli, Line 17
The last statement included within a function must be a return statement.

然后,将UDF作为

运行存在问题
function

我没有得到失败的原因。即使我把返回值放在最后,它也不起作用

2 个答案:

答案 0 :(得分:2)

替换此

    IF ( @RESULT = 1 ) 
        BEGIN
            RETURN @R
        END
    ELSE 
        BEGIN
            RETURN 0
        END

用这个

    RETURN IIF(@RESULT = 1, @R, 0)

答案 1 :(得分:0)

This link will Help you

试试这样..

CREATE FUNCTION ReturnMelli ( @Melicode CHAR(10) )
    RETURNS INT
    AS 
        BEGIN
            DECLARE @RESULT BIT
            SET @RESULT = ( SELECT  Isactive
                            FROM    TblPerson
                            WHERE   MeliCode = @Melicode
                          )
            DECLARE @R INT
            SET @R = ( SELECT   [Count]
                       FROM     TblPerson
                       WHERE    MeliCode = @Melicode
                     )
            IF ( @RESULT <> 1 ) 
                BEGIN
                    SET @R =0
                END
                   RETURN @R

        END