我在用户选中复选框时从数据库中检索数据。 DB中的值是"是"或"否"。它们都可以单独工作,但如果我单击这两个复选框,我想查看具有这两个值的所有记录。这是我的代码:
Using cmd As New OracleCommand()
Dim SQL As String = "Select * FROM MyTable "
Dim Bind_SQL As String = " Where "
Dim Activity As String
If ChkActiveYES.Checked = True Then
Activity = "YES"
SQL = String.Concat(SQL, Bind_SQL, " ACTIVE_PLAYER = :activity")
cmd.Parameters.Add(New OracleParameter("activity", Activity))
Bind_SQL = " and "
ElseIf ChkActiveNO.Checked = True Then
Activity = "NO"
SQL = String.Concat(SQL, Bind_SQL, " ACTIVE_PLAYER = :activity")
cmd.Parameters.Add(New OracleParameter("activity", Activity))
Bind_SQL = " and "
ElseIf ChkActiveYES.Checked = True And ChkActiveNO.Checked = True Then
Activity = "NO"
SQL = String.Concat(SQL, Bind_SQL, " ACTIVE_PLAYER = :activity")
cmd.Parameters.Add(New OracleParameter("activity", Activity))
Bind_SQL = " and "
Activity = "YES"
SQL = String.Concat(SQL, Bind_SQL, " ACTIVE_PLAYER = :activity")
cmd.Parameters.Add(New OracleParameter("activity", Activity))
Bind_SQL = " and "
End If
End using
我在这里缺少什么?
答案 0 :(得分:2)
任何记录如何具有YES和NO的ACTIVE_PLAYER值?它不能,所以你没有匹配。您必须使用OR来组合这两个标准。
此外,您要添加两次相同的参数名称。如果需要两个不同的值,则需要添加两个具有两个不同名称的参数。
我会提出一个不同的方法,它将解决Crush Sundae和我提出的问题。只需始终使用所有值,然后SQL确实需要是动态的,例如
cmd.CommandText = "SELECT * FROM MyTable WHERE (:p1 IS NOT NULL AND MyColumn = :p1) OR (:p2 IS NOT NULL AND MyColumn = :p2)"
cmd.Parameters.Add("p1", OracleDbType.VarChar).Value = If(ChkActiveYES.Checked, "YES", CObj(DBNull.Value))
cmd.Parameters.Add("p2", OracleDbType.VarChar).Value = If(ChkActiveNO.Checked, "NO", CObj(DBNull.Value))
答案 1 :(得分:2)
它没有去这一部分:
...
ElseIf ChkActiveYES.Checked = True And ChkActiveNO.Checked = True Then
因为它已经进入这里:
If ChkActiveYES.Checked = True Then
检查是否在if语句的第一部分中检查了两者。