vb.net - 如何检测一个日期字段值晚于/大于另一个日期字段?
问题描述
我在一个表单中有一个文本框(显示计数结果)、一个按钮(执行计数)和两个 DateTimePickers(用于日期期间从和到)。我正在为我的程序使用 MS Access 数据库,其中包含两个日期字段(date1 和 date2)。我想要的是计算有多少记录日期为(从datetimepickerfrom 和 datetimepickerto 给出的日期)。计数条件如下:如果 date2 大于或晚于 date1,则计数将基于 date2,否则基于 date1。非常感谢我的代码中的任何建议或修改。
这是我的代码,但它导致错误:“在与请求的名称或序号相对应的集合中找不到项目。”
countingconnection()
countrec = New ADODB.Recordset
With countrec
If .Fields("Date2").Value > .Fields("Date1").Value Then
.Open("select count(*) as count2 from Docstable where Date2 >=#" & DateTimePickerfrom.Value.Date & "# and Date2 <=#" & DateTimePickerto.Value.Date & "#", countcon, 2, 3)
textbox1.Text = .Fields("count2").Value
.Close()
else
.Open("select count(*) as count1 from Docstable where Date1 >=#" & DateTimePickerfrom.Value.Date & "# and Date1 <=#" & DateTimePickerto.Value.Date & "#", countcon, 2, 3)
textbox1.Text = .Fields("count1").Value
.Close()
end if
End With```
解决方案
下面是纯粹使用 SQL 并使用 ADO.NET 完成的操作:
Dim sql = "SELECT COUNT (*)
WHERE (Date1 >= Date2 AND Date1 BETWEEN @DateFrom1 AND @DateTo1)
OR (Date2 > Date1 AND Date2 BETWEEN @DateFrom2 AND @DateTo2)"
Dim dateFrom = DatePickerFrom.Value.Date
Dim dateTo = DatePickerTo.Value.Date
Dim count As Integer
Using connection As New OleDbConnection("connection string here"),
command As New OleDbCommand(sql, connection)
With command.Parameters
.Add("@DateFrom1", OleDbType.Date).Value = dateFrom
.Add("@DateFrom2", OleDbType.Date).Value = dateFrom
.Add("@DateTo1", OleDbType.Date).Value = dateTo
.Add("@DateTo2", OleDbType.Date).Value = dateTo
End With
connection.Open()
count = CInt(command.ExecuteScalar())
End Using
不幸的是,Jet 和 ACE 提供程序不能正确支持命名参数,因此您必须将每个日期值添加两次。
编辑:
您在另一个站点上发布了您正在使用 VB 2012 的帖子,但在这里您说的是 VB 2010。这可能并不重要,因为 VB 2012 可能相同,但我相当确定 VB 2010 不支持多行String
文字。在这种情况下,您可以改用 XML 文字:
Dim sql = <sql>
SELECT COUNT (*)
WHERE (Date1 >= Date2 AND Date1 BETWEEN @DateFrom1 AND @DateTo1)
OR (Date2 > Date1 AND Date2 BETWEEN @DateFrom2 AND @DateTo2)
</sql>
'...
Using connection As New OleDbConnection("connection string here"),
command As New OleDbCommand(sql.Value, connection)
'...
End Using
推荐阅读
- sql - 滑动窗口上的不同计数
- mysql - SQL 查询查找只修了 4 学分课程的学生的姓名
- winforms - 在默认应用程序 WinForms (.NET Core) 中打开文件
- azure - 在 Azure Function 中执行 Import-Module 时已加载同名程序集错误
- php - 如何通过 SQL 选择要保存到的数据库
- node.js - 我正在使用 React 创建一个表单并收到此错误
- sql - 从字符串转换日期或时间时出错
- angular - 角度翻译不适用于角度 9
- php - 使用 PHP 将图像上传到 MySQL (blob)
- sql - 如何从经典数据库转储 oracle (exp) 中提取 sql 脚本?