这是我的查询:
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
)
答案 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')
)
)