1

这是我的有效查询:

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
               )
4

3 回答 3

0

我认为你需要一个 THEN 在那里。

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
于 2013-05-24T19:00:18.520 回答
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
于 2013-05-24T19:39:06.203 回答
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') 
                           )
                     )
于 2013-05-24T19:56:09.833 回答