查询仅在日期中选择月份

Query selecting month only in date

我有一个查询,将 select 我的数据库中基于月份的所有记录。例如,我想 select 一月份的所有记录。 month() 函数对我不起作用。 ComboBox 的值为月份名称("January"、"February" 等)。我使用的是 VB 2010,我的数据库是 Microsoft Access。

query = "SELECT empid, empname, department, empdate, timeinam, " & _
        "timeoutam, lateam, timeinpm, timeoutpm, latepm, thw " & _
        "FROM tbldtr where Month(empdate) =" & cmbMonth.Text

好吧,假设您的组合框项目按 每月顺序(一月、二月、三月...)排序,那么您可以将查询写成

query = "SELECT empid, empname, department, empdate, timeinam, " & _
        "timeoutam,lateam, timeinpm, timeoutpm,latepm,thw " & _
        "FROM tbldtr where Month(empdate) =" & cmbMonth.SelectedIndex + 1

ComboBox.SelectedIndex 属性 是一个整数,告诉您当前 selected 项目的索引。这个 属性 从零开始,所以加一,匹配 VBA Month 函数

返回的数字

当然,这意味着您在此行之前的某处有一个检查,通知您的用户 select 来自组合框的内容,并且组合框本身应该 DropDownStyle 设置为 ComboBoxStyle.DropDownList 避免用户输入自己的 'month'

警告:虽然在这种情况下,(将整数转换为字符串)没有太多关注 Sql 注入最好不要沉迷于这些做法并始终使用参数化查询。

Month() 函数 returns 月数,所以你的 where 条件失败。

改为使用 like,

query = "SELECT empid, empname, department, empdate, timeinam, timeoutam,lateam, timeinpm, timeoutpm,latepm,thw FROM tbldtr where datename(month, empdate) =" & cmbMonth.Text

也尝试在 where 条件中使用 Like 语句而不是 equals,因为您可能会遇到有关字符 casing.more 讨论的问题 Like vs (=)

希望这对您有所帮助。

希望这对您有所帮助。

您还可以使用:

"FROM tbldtr where MonthName(Month(empdate)) ='" & cmbMonth.Text & "'"

不可否认,这与其他响应没有什么不同,但想要表达在执行查询之前检查所选索引以及最好使用参数,如下所示。这是 OleDb 提供者,同样适用于所有托管数据提供者,只需更改为正确的提供者即可,例如SQL服务器使用SqlClient等

加载组合框

cmbMonth.Items.AddRange(
(
    From M In System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames
    Where Not String.IsNullOrEmpty(M)).ToArray
)

示例到 运行 语句

If cmbMonth.SelectedIndex > -1 Then
    Using cn As New OleDb.OleDbConnection With
        {
            .ConnectionString = "Your connection string"
        }
        Using cmd As New OleDb.OleDbCommand With
            {
                .Connection = cn,
                .CommandText =
                    "SELECT empid, empname, department, empdate, timeinam, timeoutam, lateam, timeinpm, timeoutpm, latepm, thw " &
                    "FROM tbldtr where Month(empdate) = @SelectedMonth"
            }
            cmd.Parameters.Add(New OleDb.OleDbParameter With
                {
                    .ParameterName = "@SelectedMonth",
                    .DbType = DbType.Int32,
                    .Value = cmbMonth.SelectedIndex + 1
                }
            )
            ' continue
        End Using
    End Using
End If