【问题标题】:An expression of non-boolean type specified in a context where a condition is expected, near 'and'在预期条件的上下文中指定的非布尔类型的表达式,靠近“和”
【发布时间】:2015-09-06 07:59:00
【问题描述】:

我已将我的数据库从Access 转换为Sql,因为Sql 不接受format(),因此显示错误。

这是我的代码:

DefaultStr = "" &
"SELECT StudentAccount.Dated, StudentAccountS.StAdmNo, StudentAccountS.StClass, " &
"StudentAccountS.StName, StudentAccount.Perticular, StudentAccount.Amount,StudentAccount.Remark,StudentAccount.PayMode,TransactionID " &
"FROM (StudentAccount LEFT OUTER JOIN StudentAccountS ON StudentAccount.SSID = StudentAccountS.SSID) " &
"WHERE (StudentAccount.Debit) and (StudentAccount.Dated Between " &
"#" & Format(DateFrom, "MM/dd/yyyy") & "# AND #" & Format(DateTo, "MM/dd/yyyy") & "#)"


Select Case SIndex
    Case 0
        SelStr = " AND (StudentAccount.PayMode = '" & OptionStr & "') Order By StudentAccount.Dated"
    Case 1
        SelStr = " AND (StudentAccount.Perticular = '" & OptionStr & "') Order By StudentAccount.Dated"
    Case 2, 3
        SelStr = " AND (StudentAccount.TransType = '" & filterStr & "') Order By StudentAccount.Dated"
    Case Else
        SelStr = Nothing
End Select

Da = New SqlDataAdapter(DefaultStr & SelStr, Conn)
Ds = New DataSet
Da.Fill(Ds)

【问题讨论】:

  • mssql 中,当您存储date(或datetime)值时,不要使用#(如Access),而是使用单引号。什么是DateToDateFrom,变量?如果他们使用这样的东西:'" & String.Format("{0:MM/dd/yyyy}", DateTo) & "'
  • 我还要补充一点,您不应该使用字符串连接来构建 sql 命令。使用参数化的 sql。看到这个stackoverflow.com/questions/306668/…
  • 这也会抛出同样的错误
  • 错误出现在这部分代码中:WHERE (StudentAccount.Debit) and (StudentAccount.DatedStudentAccount.Debit 似乎不是布尔值,因此不能与and 一起使用。

标签: vb.net sql-server-2008


【解决方案1】:

你必须使用这样的东西:

Dim CMD As SqlClient.SqlCommand = Conn.CreateCommand
Dim dtStart As DateTime = New DateTime(2015, 9, 6, 10, 1, 0)
Dim dtEnd As DateTime = New DateTime(2015, 9, 6, 11, 0, 0)

CMD.CommandText = "SELECT * FROM Table1 WHERE Date BETWEEN '" & dtStart.ToString("yyyy-MM-dd HH:mm:ss") & "' AND '" & _
                dtEnd.ToString("yyyy-MM-dd HH:mm:ss") & "'"
Dim DA As New SqlClient.SqlDataAdapter
DA.SelectCommand = CMD
Dim DT As New DataTable
DA.Fill(DT)

但是,我建议您开始学习 SqlParameter 查询(更可靠,例如处理 sql 注入)。只需使用类似的东西:

CMD.Parameters.Add("@DateStart", SqlDbType.DateTime2, 20).Value = dtStart
CMD.Parameters.Add("@DateEnd", SqlDbType.DateTime2, 20).Value = dtEnd
CMD.CommandText = "SELECT * FROM Table1 WHERE Date BETWEEN @DateStart AND @DateEnd"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    • 2015-10-23
    • 1970-01-01
    • 2011-09-22
    • 2013-02-11
    相关资源
    最近更新 更多