我在case语句中实现了多个条件,如下所示,
select officied from budgettable
where budgetid = case @budgetid when 7 then 7
when 7 then 8
when 7 then 10
when 8 then 6
end
但它没有给我任何结果。如果我将预算ID称为7
,则查询应返回8,10,7
预算ID。上述查询有什么问题吗?
答案 0 :(得分:4)
我怀疑你想要这样的东西:
where budgetid = @budgetid or
(@budgetid = 7 and budgetid in (7, 8, 10)) or
(@budgetid = 8 and budgetid = 6)
您的查询失败,因为@budgetid
除了7或8之外的所有值,case
都会返回NULL
- 这被视为错误。
答案 1 :(得分:2)
一种选择是使用case
作为布尔表达式,在满足条件时返回1
:
select officied from budgettable
where 1 = case
when @budgetid = budgetid then 1
when @budgetid = 7 and budgetid in (7,8,10) then 1
when @budgetid = 8 and budgetid in (6,8) then 1
end
这会将@budgetid
7返回的结果扩展为包含8和10。
答案 2 :(得分:2)
这不是答案。我只是想表明CASE WHEN如何运作,所以你看到了你的错误。您的查询评估Sub test_Wanceslas()
Dim Ws As Worksheet, _
Rg As Range, _
LastRow As Long, _
Count As Long, _
ii As Long
ii = 21 ' first page break
Set Ws = ActiveSheet
With Ws
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
Count = LastRow
Set Rg = .Range("A1", "K" & Count) 'The range of the document
If LastRow > 30 Then ' count is the number of row. Break at every 15 rows
.ResetAllPageBreaks
.PageSetup.PrintArea = Rg.Address
While Count > 0 And ii < LastRow
If Count > 15 Then ' no page break if there is less than 15 rows left
'.Rows(ii).PageBreak = xlPageBreakManual
.HPageBreaks.Add Before:=.Rows(ii)
End If
ii = ii + 15
Count = Count - 15
Wend
End If
End With
End Sub
,如下所示:
然后将结果与case @budgetid
进行比较。对于NULL,这永远不会成立。所以你最终得到:
= budgetid
答案 3 :(得分:1)
这会有效!!
SELECT
officied
FROM
budgettable
WHERE
1 = 1
AND
1 = CASE
WHEN
@budgetid = budgetid THEN 1
WHEN
(@budgetid = 7 AND budgetid IN (7,8,10)) THEN 1
WHEN
(@budgetid = 8 AND budgetid IN (6,8) THEN) 1
END
更好的解决方案:添加新列 is_budget_calculated (数据类型BIT)并将其更新为0并保持为1。