【发布时间】:2020-06-22 18:07:04
【问题描述】:
我想统计本月和每个月的 PPM 订单数量,这是我的代码,但运行时出现错误
“#”附近的语法不正确
我需要大致了解如何根据日期进行选择,我讨厌使用日期,请帮助我。谢谢
Dim dtp0 As New DateTimePicker
Dim dtp1 = dtp0.Value
Dim count_m As Integer
Dim cmd1 As New SqlCommand("SELECT count ([id]) FROM [machines] where ppm1 = #" & dtp1.Day & "/" & dtp1.Month & "/" & dtp1.Year & " # and [takhen] is NULL and [irga] is NULL", connsql)
Dim da1 As New SqlDataAdapter(cmd1)
Dim dt1 As New DataTable
da1.Fill(dt1)
If dt1.Rows.Count > 0 Then
connsql.Open()
count_m = Convert.ToInt32(cmd1.ExecuteScalar())
connsql.Close()
Label68.Text = count_m.ToString
End If
【问题讨论】:
-
您在关闭
#标记之前有一个额外的空间。" # and [takhen] is NULL -
不管语法错误如何,最好为查询使用参数,而不是尝试通过字符串连接来构建 where 条件。将为您节省一大堆头痛
-
您应该使用参数化查询来传递您的日期值。对于您当前的代码,您认为在 SET DATEFORMAT MDY 生效的服务器上会发生什么?参数化查询避免了像这样的小问题,同时避免了大的 SQL 注入问题。
-
添加到@AlwaysLearning 的评论,见why parameters are a best practice。
标签: sql-server vb.net