Microsoft Access 2013条件参数查询

时间:2015-04-10 18:30:27

标签: sql vba ms-access where-clause

我有一个表单,它使用两个参数来搜索/过滤掉可用的案例。有三个控件:txtCaseFiler,cboClients和lstCases。

cboClients显示仅列出当前分配给案例的客户的列表

lstCases显示可过滤的案例列表

在txtCaseFilter中我为onChange事件提供了VBA来重新查询lstCases以及lstCases的行源中的以下条件,而在cboClients上我在AfterUpdate事件上有相同的VBA。

LIKE“”& [FORMS]![frmCaseSearch]![txtCaseFilter]。[Text]& “

这部分工作正常。

考虑到一个人可能想要搜索尚未分配客户端的案例,想要以忽略cboClient的方式为lstCases构建查询,如果它是空的,但只过滤掉案例( s)选择一个客户时的客户。

我试过这个:Nz([Forms]![frmCaseSearch]![cboClients],[ClientID])如果我只查找已分配客户端的案例,但没有引入任何案例,那么它可以正常工作客户端。

这是迄今为止我所拥有的SQL。

SELECT tblCases.CaseNumber, tblCasesClients.ClientID
FROM tblCases LEFT JOIN tblCasesClients ON (tblCases.AgencyID = tblCasesClients.AgencyID) AND (tblCases.CaseNumber = tblCasesClients.CaseNumber)
WHERE (((tblCases.CaseNumber) Like "*" & [FORMS]![frmCaseSearch]![txtCaseFilter].[Text] & "*") AND ((tblCasesClients.ClientID)=Nz([Forms]![frmCaseSearch]![cboClients],[ClientID])))
ORDER BY tblCases.CaseNumber;

如何编写此查询,以便它忽略cboClients,如果它为null,但如果不是则使用它?我考虑的唯一其他选项是编写一个VBA函数来返回Row Source字符串,但这看起来有点过分。

2 个答案:

答案 0 :(得分:1)

考虑使用VBA动态构建查询:

strSQL = "SELECT tblCases.CaseNumber, tblCasesClients.ClientID" 
strSQL = strSQL & " FROM tblCases"
strSQL = strSQL & " LEFT JOIN tblCasesClients ON (tblCases.AgencyID = tblCasesClients.AgencyID)"
strSQL = strSQL & " AND (tblCases.CaseNumber = tblCasesClients.CaseNumber)"
strSQL = strSQL & " WHERE (((tblCases.CaseNumber) Like '*" & [Forms]![frmCaseSearch]![txtCaseFilter] & "*')" 

If Not IsNull([Forms]![frmCaseSearch]![cboClients]) Then
    strSQL = strSQL & " AND ((tblCasesClients.ClientID)=([Forms]![frmCaseSearch]![cboClients])))"
Else 
    strSQL = strSQL & ")"
End If

strSQL = strSQL & " ORDER BY tblCases.CaseNumber;"

Forms!frmCaseSearch!lstCases.RowSource = strSQL

答案 1 :(得分:0)

这对你有用吗?

SELECT tblCases.CaseNumber, 
    tblCasesClients.ClientID
FROM tblCases 
LEFT JOIN tblCasesClients 
ON (tblCases.AgencyID = tblCasesClients.AgencyID) 
    AND (tblCases.CaseNumber = tblCasesClients.CaseNumber)
WHERE 
    tblCases.CaseNumber Like "*" & [FORMS]![frmCaseSearch]![txtCaseFilter].[Text] & "*"
    AND (tblCasesClients.ClientID = [Forms]![frmCaseSearch]![cboClients])
        or nz([Forms]![frmCaseSearch]![cboClients].[Text],"")="")
ORDER BY tblCases.CaseNumber;