基于检查复选框的组合构建字符串



在表格上我有3个复选框-chk1chk2,&chk3

根据盒子的组合,将构建SQL语句的WHERE子句。

所以,如果仅检查chk1,我需要我的字符串为: -

where x=1

但是,如果检查了chk1chk2,我需要我的字符串为: -

where x=1 or x=2

构建字符串的最佳方法是什么?我尝试了Ifs Ifs Ifs,但看起来很混乱,我敢肯定必须有更好的方法。

我构建SQL子句的通常方式是以下方式:

Dim strWhere As String
strWhere = "WHERE 1=1" 'Always true
If chk1 Then
    strWhere = strWhere & " OR x=1"
End If
If chk2 Then
    strWhere = strWhere & " OR x=2"
End If
If chk3 Then
    strWhere = strWhere & " OR x=3"
End If
strWhere = Replace(strWhere, "1=1 OR ", "") 'Remove always true if something has been set

这样,您可以通过添加额外的标准轻松地扩展其中的子句。

在这种情况下,由于您仅比较一个值,我会使用以下内容:

Dim strWhere As String
strWhere = "WHERE x IN (Null" 'In(Null) is valid, but will return Null = false if null and false if any other value
If chk1 Then
    strWhere = strWhere & ",1"
End If
If chk2 Then
    strWhere = strWhere & ",2"
End If
If chk3 Then
    strWhere = strWhere & ",3"
End If
strWhere = strWhere & ")"

当没有检查时,这些行为会有所不同。第一种方法将在这种情况下返回所有内容,第二个方法。

最新更新