MS Access:WHERE子句中的条件(如果参数为null,则默认使用)

时间:2012-05-31 08:30:21

标签: ms-access parameters where-clause

我需要一个参数化的交叉表查询。除参数部分外,我大部分时间都在研究它。 我有四个要应用的参数:ChangeID和variant1,variant2和variant3。 ChangeID是必需的,需要由用户填写。 Variant1..3是可选的:要么用户填充一到三个变体,要么(如果variant1为null),则应使用默认值。

默认是预定义变体的替代方案,实际填充的变体也应作为替代方案应用。

我想到了这样的事情:

PARAMETERS ChangeID Text (7), variant1 Text (10), variant2 Text (10), variant3 Text (10);
TRANSFORM Sum([Qty]*[inout]) AS QtyInOut
SELECT MatByOrder.CHpoint, MatByOrder.PN, MatByOrder.Description, MatByOrder.Price, MatByOrder.UoM
FROM Variants INNER JOIN MatByOrder ON Variants.BO = MatByOrder.BO

WHERE 
    (MatByOrder.CHpoint=ChangeID) AND 
    (IIF(isNull([variant1]); 
        (Variants.Variant="B100") OR (Variants.Variant="B200") OR (Variants.Variant="B300") OR (Variants.Variant="B400") OR (Variants.Variant="B500");
        (Variants.Variant=[variant1]) OR (Variants.Variant=[variant2]) OR (Variants.Variant=[variant3])
       )
    )

GROUP BY MatByOrder.CHpoint, MatByOrder.PN, MatByOrder.Description, MatByOrder.Price, MatByOrder.UoM

但它不起作用。问题当然是WHERE子句中的IIF。

完成此任务的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

这应该有效:

WHERE 
    (MatByOrder.CHpoint=ChangeID) AND 
    (
       ( ([variant1] IS NULL) AND (Variants.Variant IN ('B200', 'B300', 'B400', 'B500')) )
       OR    
       ( ([variant1] IS NOT NULL) AND (Variants.Variant IN ([variant1], [variant2], [variant3])) )
    )

答案 1 :(得分:0)

我在我的语言环境中测试了Instr的想法,其中逗号是参数分隔符,它适用于我。我认为你应该用简单的查询尝试这个想法,看看它是否适合。

这个想法是:

Instr(Nz(Var,String) & ",",Field & ",")>0

在字段中添加逗号或其他分隔符对于避免错误匹配非常重要。

PARAMETERS ChangeID Text (7), variant1 Text (10), variant2 Text (10), variant3 Text (10);
TRANSFORM Sum([Qty]*[inout]) AS QtyInOut
SELECT MatByOrder.CHpoint, MatByOrder.PN, MatByOrder.Description, MatByOrder.Price, MatByOrder.UoM
FROM Variants INNER JOIN MatByOrder ON Variants.BO = MatByOrder.BO

WHERE 
    (MatByOrder.CHpoint=ChangeID) AND 
    (Instr(Nz([variant1],"B100,B200,B300,B400,B500" 
               & [variant1] & "," & [variant2] & "," 
               & [variant3]) & ",", MatByOrder.CHpoint) > 0
    )

GROUP BY MatByOrder.CHpoint, MatByOrder.PN, MatByOrder.Description, MatByOrder.Price, MatByOrder.UoM