我有一个有3个表的数据库(ListOfDevice,DeviceType,Employee)。
ListOfDevice表
某些记录没有employeeID,并且在设备状态字段中标记为“已损坏”。
我创建了一个查询并将其命名为“QryDeviceLists”,在此查询中我导入了这3个表并开始过滤查询和报告结果。我使用“Like”和Wildcard进行过滤。
示例:Like"*" &[Form]![FormName]![ControlName or Combo box name]&"*"
我在这里尝试过滤的是DeviceType,EmployeeID和DeviceStatus。我希望这个过滤器工作的方式是通过组合框,我有一个表单,我命名为过滤器,在这个表单内是3个未绑定的组合框链接到这3个表。以下是我将如何生成报告:
以下是我在尝试使用组合框提取报告时遇到的问题。
注意:我没有任何VBA经验,而且我正在使用Access 2013-2016
以下是查询SQL Lines SELECT ListOfDevices.ID, ListOfDevices.DeviceName, ListOfDevices.[Device Model], DeviceType.DeviceType, Employee.FirstName, ListOfDevices.DeviceStatus
FROM Employee RIGHT JOIN (DeviceType RIGHT JOIN ListOfDevices ON DeviceType.ID = ListOfDevices.DeviceType) ON Employee.ID = ListOfDevices.EmployeeID
WHERE (((DeviceType.DeviceType) Like "*" & [Forms]![filter]![CboDevType] & "*") AND ((Employee.FirstName) Like "*" & [Forms]![filter]![CboEmp] & "*") AND ((ListOfDevices.DeviceStatus) Like "*" & [Forms]![filter]![CboStat] & "*"));
考虑这个纯SQL解决方案,WHERE
子句指向组合框(没有LIKE
表达式)。如果组合框是空的,NZ()
会返回该区域。如果报表/表单绑定到此查询,则不需要VBA。
QryDeviceLists
SELECT l.ID, l.DeviceName, l.[Device Model], d.DeviceType, e.FirstName, l.DeviceStatus
FROM Employee e
RIGHT JOIN (DeviceType d
RIGHT JOIN ListOfDevices l ON d.ID = l.DeviceType)
ON e.ID = l.EmployeeID
WHERE ((d.DeviceType) = NZ([Forms]![filter]![CboDevType], d.DeviceType)
AND (e.ID) = NZ([Forms]![filter]![CboEmp], e.FirstName)
AND (l.DeviceStatus) = NZ([Forms]![filter]![CboStat], l.DeviceStatus))
OR
(
IIF([Forms]![filter]![CboDevType] IS NULL, d.DeviceType IS NULL, [Forms]![filter]![CboDevType] = d.DeviceType)
AND IIF([Forms]![filter]![CboEmp] IS NULL, e.ID IS NULL, [Forms]![filter]![CboEmp] = e.ID)
AND IIF([Forms]![filter]![CboStat] IS NULL, l.DeviceStatus IS NULL, [Forms]![filter]![CboStat] = l.DeviceStatus)
)
OR
(
IIF([Forms]![filter]![CboDevType] IS NULL AND
[Forms]![filter]![CboEmp] IS NULL AND
[Forms]![filter]![CboStat] IS NULL,
d.DeviceType IS NULL OR e.ID IS NULL OR l.DeviceStatus IS NULL ,
[Forms]![filter]![CboDevType] = d.DeviceType OR
[Forms]![filter]![CboEmp] = e.ID OR
[Forms]![filter]![CboStat] = l.DeviceStatus)
)
笔记:
Requery
(可用作宏命令)NULL
。我从其他论坛找到了一个我无法提及的解决方案,因为如果允许的话,我不会这样做。但是,这是我用来解决问题的SQL Line。
SELECT ListOfDevices.ID, ListOfDevices.DeviceName, ListOfDevices.[Device Model], DeviceType.DeviceType, Employee.FirstName, ListOfDevices.DeviceStatus
FROM Employee RIGHT JOIN (DeviceType RIGHT JOIN ListOfDevices ON DeviceType.ID = ListOfDevices.DeviceType) ON Employee.ID = ListOfDevices.EmployeeID
WHERE ((([DeviceType.DeviceType] Like "*" & [Forms]![filter]![CboDevType] & "*" Or [Forms]![filter]![CboDevType] Is Null)=True) AND (([FirstName]=[Forms]![filter]![CboEmp] Or [Forms]![filter]![CboEmp] Is Null)=True) AND (([DeviceStatus]=[Forms]![filter]![CboStat] Or [Forms]![filter]![CboStat] Is Null)=True));
感谢Parfait先生的出色表现。