如何在SQL中构建嵌套的IF语句

时间:2014-05-27 14:44:59

标签: sql if-statement

我有一个问题,我想在某些情况下使用某些查询,但无法使语法工作。我猜这是因为多个IF,但有人可以启发我,请问如何解决它?

    IF smthn = 1 THEN
     SELECT stuff ,
      IFNULL(t3.value3,0.00) av_value,
       IF (t1.value1= t2.value2, t1.value1+ IFNULL(t3.value3,0.00) , t1.value1) kumul ,)
    t2.value2 summa
    FROM tbl_1 t1

    END//
        END IF;

   IF smthn = 2 THEN
     //make the query with different calculations//

    END//
        END IF;

由于

2 个答案:

答案 0 :(得分:1)

IF smthn = 1 THEN
    SELECT
        stuff,
        IFNULL(t3.value3,0.00) av_value,
        IF (t1.value1= t2.value2, t1.value1+ IFNULL(t3.value3,0.00) , t1.value1) kumul , -- Lose the extra closing bracket here.
        t2.value2 summa
FROM tbl_1 t1

-- You don't need END before your END IF
-- END//
END IF;

IF smthn = 2 THEN
    -- make the query with different calculations//

END IF;

您可以尝试使用此代码的变体吗?我已经评论了我改变的界限。

答案 1 :(得分:-1)

SQL Server 语法

IF smthn = 1 
BEGIN
 SELECT stuff ,
 ISNULL(t3.value3,0.00) av_value,
 case when (t1.value1= t2.value2 then t1.value1+ ISNULL(t3.value3,0.00) t1.value1) kumul ,)t2.value2 summa
FROM tbl_1 t1
END
ELSE IF smthn = 2
BEGIN
     --make the query with different calculations//
END