【问题标题】:How to search between two dates and time from sql in vb,net?如何在vb,net中的sql中搜索两个日期和时间?
【发布时间】:2019-02-05 18:31:35
【问题描述】:

我正在尝试创建一个 Crystal Report,我可以在其中搜索由 datetimepicker1 和 datetimepicker2 选择的两个日期。 MySql 数据库日期列已像这样(12/26/2018 3:28:30 PM)保存了日期时间。我的选择语句和参数不正确。我该怎么做?

Private Function GetData() As billing

    Dim x = Form25.DateTimePicker1.Value.Date.ToString("MM-dd-yyyy")

    Dim y = Form25.DateTimePicker2.Value.Date.ToString("MM-dd-yyyy")

    Dim constr As String = ("server= PANKAJ\SQLEXPRESS; database = pankaj billing software; integrated security=True")

    Using con As New SqlConnection(constr)

        Using cmd As New SqlCommand("select goldrate,date,itemcode,karat,category,item,qty,grossweight,netweight,discountrs,finalamount from allsaledata where date >= @date AND date <= @date", con)
            cmd.Parameters.AddWithValue("@date", x And y)


            Using sda As New SqlDataAdapter()
                cmd.Connection = con
                sda.SelectCommand = cmd
                Using dsCustomers As New billing()
                    sda.Fill(dsCustomers, "DataTable1")
                    Return dsCustomers

                End Using
            End Using
        End Using
    End Using
End Function

【问题讨论】:

    标签: vb.net


    【解决方案1】:

    当您对 Date 类型的列执行查询时,要做的第一件事就是不要传递字符串类型的参数。这将迫使数据库引擎进行自己的转换,并且您获得错误转换的风险非常高。

    所以你应该传递 DateTime 类型的参数,你需要两个参数,因为你有两个日期限制要检查

    ' Do not convert to strings here. Work with dates
    Dim x = Form25.DateTimePicker1.Value.Date
    Dim y = Form25.DateTimePicker2.Value.Date
    
    Using cmd As New SqlCommand("select goldrate,date,itemcode,karat,
                                        category,item,qty,grossweight,
                                        netweight,discountrs, finalamount 
                                 from allsaledata 
                                 where date >= @init AND date <= @end", con)
    
        cmd.Parameters.Add("@init", SqlDbType.Date).Value = x
        cmd.Parameters.Add("@end", SqlDbType.Date).Value = y
    

    要注意的另一件事是,如果您使用不带时间部分的 DateTime,那么您的查询可能会排除最后一天的日期。

    例如,如果您的结束日期为 02/05/2019 00:00:00,则日期和时间为 02/05/2019 19:40:00 的记录将不会包含在结果中因为 00:00:000 的时间是午夜,而其他时间是午夜之后。
    如果您想避免这种情况,请在结束日期中添加一天,如下所示

    Dim y = Form25.DateTimePicker2.Value.Date.AddDay(1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      • 2021-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-24
      相关资源
      最近更新 更多