在这里找到了几个类似的问题,但无法弄清楚如何应用于我的场景。
我的函数有一个名为@IncludeBelow的参数。值为 0 或 1 (BIT)。
我有这个查询:
SELECT p.*
FROM Locations l
INNER JOIN Posts p
on l.LocationId = p.LocationId
WHERE l.Condition1 = @Value1
AND l.SomeOtherCondition = @SomeOtherValue
如果@IncludeBelow 为0,我需要这样的查询:
SELECT p.*
FROM Locations l
INNER JOIN Posts p
on l.LocationId = p.LocationId
WHERE l.Condition1 = @Value1
AND l.SomeOtherCondition = @SomeOtherValue
AND p.LocationType = @LocationType -- additional filter to only include level.
如果 @IncludeBelow 为 1,则需要排除最后一行。(即不应用过滤器)。
我猜它需要是一个CASE
语句,但无法弄清楚语法。
这是我尝试过的:
SELECT p.*
FROM Locations l
INNER JOIN Posts p
on l.LocationId = p.LocationId
WHERE l.Condition1 = @Value1
AND l.SomeOtherCondition = @SomeOtherValue
AND (CASE @IncludeBelow WHEN 0 THEN p.LocationTypeId = @LocationType ELSE 1 = 1)
显然这是不正确的。
什么是正确的语法?