SQL 单个 IF 语句中的多个条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15429983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 14:17:25  来源:igfitidea点击:

Multiple condition in single IF statement

sqlsql-serversql-server-2008

提问by Billa

I want to add multiple condition in single IF statement in SQL.

我想在 SQL 的单个 IF 语句中添加多个条件。

I am not good in SQL & referred some example, all are showing only one condition in IF.

我不擅长 SQL & 提到了一些例子,所有在 IF 中都只显示一个条件。

Here is my procedure.

这是我的程序。

CREATE PROCEDURE [dbo].[AddApplicationUser]    
(  
@TenantId BIGINT,  
@UserType TINYINT,
@UserName  NVARCHAR(100),  
@Password NVARCHAR(100)  
)  

AS    

BEGIN   

IF ((@TenantId IS NULL)  AND (@UserType=0 OR @UserType=1) )
  RAISERROR('The value for @TenantID should not be null', 15, 1) -- with log 

Is this correct syntax in SQL for multiconditions in IF?

对于 IF 中的多条件,SQL 中的这种语法是否正确?

回答by Martin Smith

Yes that is valid syntax but it may well not do what you want.

是的,这是有效的语法,但它很可能无法满足您的需求。

Execution will continue after your RAISERRORexcept if you add a RETURN. So you will need to add a block with BEGIN ... ENDto hold the two statements.

执行将在您之后继续,RAISERROR除非您添加RETURN. 所以你需要添加一个块BEGIN ... END来保存这两个语句。

Also I'm not sure why you plumped for severity 15. That usually indicates a syntax error.

此外,我不确定您为什么将严重性设置为 15。这通常表示语法错误

Finally I'd simplify the conditions using IN

最后我会使用简化条件 IN

CREATE PROCEDURE [dbo].[AddApplicationUser] (@TenantId BIGINT,
                                            @UserType TINYINT,
                                            @UserName NVARCHAR(100),
                                            @Password NVARCHAR(100))
AS
  BEGIN
      IF ( @TenantId IS NULL
           AND @UserType IN ( 0, 1 ) )
        BEGIN
            RAISERROR('The value for @TenantID should not be null',15,1);

            RETURN;
        END
  END 

回答by www

Yes it is, there have to be boolean expresion after IF. Here you have a direct link. I hope it helps. GL!

是的,IF 之后必须有布尔表达式。这里有一个直接链接。我希望它有帮助。高!