我们可以在SQL Server 2008中的ELSE IF语句中编写IN子句

时间:2014-12-19 06:02:27

标签: sql sql-server sql-server-2008 function stored-procedures

我正在编写一个标量值函数,并且我正在传递电子邮件和methodID,它将返回INT,现在我需要根据methodID检查条件,以便我返回如下所示

ALTER FUNCTION FN_EMPCHECK
(
    @EmailAddress VARCHAR(150),
    @methodID INT
)
RETURNS INT
AS
BEGIN
    DECLARE @IsResult INT

    IF(@methodID = 101)
    BEGIN
        SELECT @IsResult = ID FROM table1 WHERE EmailAddress = @EmailAddress
    END
    ELSE IF(@methodID = 102 OR @methodID = 104 OR @methodID = 105 OR @methodID = 107 OR @methodID = 108
                OR @methodID = 109 OR @methodID = 110 OR @methodID = 111 OR @methodID = 114)
    BEGIN
        SELECT @IsResult = ID FROM table2 WHERE EmailAddress = @EmailAddress
    END
    ELSE IF(@methodID = 103 OR @methodID = 106 OR @methodID = 112 OR @methodID = 113)
    BEGIN
        SELECT @IsResult = ID FROM table3 WHERE EmailAddress = @EmailAddress
    END

    RETURN @IsResult
END

需要关于Else的建议如果在上述函数中声明天气是正确的方式,或者我可以用任何其他简单的方式编写(编写许多OR条件)

2 个答案:

答案 0 :(得分:2)

您可以在ELSE IF条件中使用 IN 而不是多个 OR 运算符,请查看以下代码

ALTER FUNCTION FN_EMPCHECK
(
    @EmailAddress VARCHAR(150),
    @methodID INT
)
RETURNS INT
AS
BEGIN
    DECLARE @IsResult INT

    IF(@methodID = 101)
    BEGIN
        SELECT @IsResult = ID FROM table1 WHERE EmailAddress = @EmailAddress
    END
    ELSE IF(@methodID IN (102, 104, 105, 107, 108, 109, 110, 111, 114))
    BEGIN
        SELECT @IsResult = ID FROM table2 WHERE EmailAddress = @EmailAddress
    END
    ELSE IF(@methodID IN (103 ,106, 112, 113))
    BEGIN
        SELECT @IsResult = ID FROM table3 WHERE EmailAddress = @EmailAddress
    END

    RETURN @IsResult
END

答案 1 :(得分:0)

是您可以在If语句中使用 IN

ALTER FUNCTION FN_EMPCHECK
(
    @EmailAddress VARCHAR(150),
    @methodID INT
)
RETURNS INT
AS
BEGIN
DECLARE @IsResult INT

IF(@methodID = 101)
BEGIN
    SELECT @IsResult = ID FROM table1 WHERE EmailAddress = @EmailAddress
END
ELSE IF @methodID IN (102, 104, 105, 107, 108, 109, 110, 111, 114)
BEGIN
    SELECT @IsResult = ID FROM table2 WHERE EmailAddress = @EmailAddress
END
ELSE IF @methodID IN (103 ,106, 112, 113)
BEGIN
    SELECT @IsResult = ID FROM table3 WHERE EmailAddress = @EmailAddress
END

RETURN @IsResult
END