事务SQL中IF下的多个条件

时间:2018-05-03 12:18:34

标签: tsql

我正在尝试使用'和'在If条件中如下:

Begin
If condition1 and condition2 
then begin result1 
end else begin result2;
End;
end;

声明中有什么问题。任何人都能帮忙解决这个问题吗?谢谢!

3 个答案:

答案 0 :(得分:1)

作为一个疯狂的猜测,失去了'然后' (SFrejofsky的评论),并失去了第一个;它位于begin..end块的内部。

此外,如果块中只有可执行行,则不需要begin..end,因此您的代码应如下所示

If condition1 and condition2 
  result1 
else 
  result2

答案 1 :(得分:1)

删除THEN。实施例

DECLARE @variable INT = 0
DECLARE @variable2 INT = 10

IF @variable > 0 AND @variable2 > 0
BEGIN

    SELECT 'Condition was met'

END
ELSE
BEGIN

    SELECT 'Condition was not met'

END

如果您想链接IFs

DECLARE @variable INT = 0
DECLARE @variable2 INT = 10

IF @variable > 0 AND @variable2 > 0
BEGIN

    SELECT 'Condition 1 was met'

END
ELSE IF @variable = 0 AND @variable2 > 0
BEGIN

    SELECT 'Condition 2 was met'

END
ELSE
BEGIN

    SELECT 'No condition was met'

END

此外,如果您只需要一个语句,则可以避免使用BEGIN ... END,但如果表达式很长,则可能很难理解。

DECLARE @variable INT = 0
DECLARE @variable2 INT = 10

IF @variable > 0 AND @variable2 > 0
    SELECT 'Condition was met'
ELSE
    SELECT 'Condition was not met'

答案 2 :(得分:-1)

Json_content["key_in_json_file"]