无法向SQL查询添加IF语句

时间:2013-05-24 18:56:21

标签: sql azure-sql-database

这是我的查询:

Select AsOfDate, Family, Type, DocID, Title, Date1, Date2, Date3, Stat1, Stat2, Stat3
FROM DocumentationData
WHERE Type = @Type 
AND Family = @Family
AND AsOfDate = (SELECT Max(AsOfDate)
                       FROM DocumentationData
                       WHERE AsOfDate <= @CurrentDate )

我想添加一个条件。如果@ActiveOnly为真,我想要一个额外的Usage ='Active'约束。

这是我正在尝试的,但它会导致错误:

Select AsOfDate, Family, Type, DocID, Title, Date1, Date2, Date3, Stat1, Stat2, Stat3
FROM DocumentationData
WHERE Type = @Type 
AND Family = @Family
AND AsOfDate = (IF (@ActiveOnly = 'TRUE')
                BEGIN
                SELECT Max(AsOfDate)
                FROM DocumentationData
                WHERE AsOfDate <= @CurrentDate
                AND Usage = 'Active'
                END
                ELSE
                BEGIN
                SELECT Max(AsOfDate)
                FROM DocumentationData
                WHERE AsOfDate <= @CurrentDate
                END
               )

3 个答案:

答案 0 :(得分:0)

我认为你需要那个。

AND AsOfDate =  IF (@ActiveOnly = 'TRUE') 
                THEN                 
                SELECT Max(AsOfDate)
                FROM DocumentationData
                WHERE AsOfDate <= @CurrentDate
                AND Usage = 'Active'

                ELSE
                BEGIN
                SELECT Max(AsOfDate)
                FROM DocumentationData
                WHERE AsOfDate <= @CurrentDate

                END IF

答案 1 :(得分:0)

如果没有其他选项,我发现将整个事情复制到这样的两个查询中有效:

IF(@ActiveOnly = 'TRUE')
BEGIN
Select AsOfDate, Family, Type, DocID, Title, Date1, Date2, Date3, Stat1, Stat2, Stat3
FROM DocumentationData
WHERE Type = @Type 
AND Family = @Family
AND AsOfDate =  (SELECT Max(AsOfDate)
                      FROM DocumentationData
                      WHERE AsOfDate <= @CurrentDate
                      AND Usage = 'Active'
                      )
END                          
ELSE
BEGIN
Select AsOfDate, Family, Type, DocID, Title, Date1, Date2, Date3, Stat1, Stat2, Stat3
FROM DocumentationData
WHERE Type = @Type 
AND Family = @Family
AND AsOfDate =  (SELECT Max(AsOfDate)
                          FROM DocumentationData
                          WHERE AsOfDate <= @CurrentDate
                          )
END

答案 2 :(得分:0)

我认为您应该可以在不使用IF...THEN...ELSE的情况下执行此操作。您与第一次查询尝试很接近,只需使用其他子句将类似的IF逻辑应用于子查询中的WHERE

SELECT AsOfDate, Family, Type, DocID, Title, Date1, Date2, Date3, Stat1, Stat2, Stat3
  FROM DocumentationData
 WHERE Type = @Type 
   AND Family = @Family
   AND AsOfDate =  (SELECT Max(AsOfDate)
                      FROM DocumentationData
                     WHERE AsOfDate <= @CurrentDate
                       AND ( ( @ActiveOnly = 'TRUE' AND Usage = 'Active') 
                             OR (@ActiveOnly <> 'TRUE') 
                           )
                     )