查询日期和时间

时间:2018-05-10 17:46:26

标签: sql sql-server vb.net sql-server-2014

在我的数据库中,使用SQL Server 2014,其中包含一个名为TableOberge的表,其列名为Date-In,类型为Date,第二列名为Hour-In } Time(7)类型。 使用此查询,我想在DatagridView1中显示已达到日期和时间的记录...但我无法正确显示它们。

请帮助:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dbb_Connection()
    Using InfoAdapter As New SqlDataAdapter("SELECT * FROM TABLEOBERGE WHERE [DATE_IN] >= CONVERT(date, GETDATE()) AND [HOUR_IN] >= convert(time(0),getDate())", StrCon)
        InfoTable = New DataTable
        InfoAdapter.Fill(InfoTable)
        DataGridView1.DataSource = InfoTable
    End Using
End Sub

我的添加记录代码:

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dbb_Connection()
    Using Command As New SqlCommand With {.Connection = StrCon}
        With Command.Parameters
            Command.CommandText = "INSERT INTO [TABLEOBERGE] ([ID], [FIRSTNAME], [PHONE], [ADRESSE], [DATE_OUT], [HOUR_OUT], [DATE_IN], [HOUR_IN]) VALUES (@ID, @FIRSTNAME, @PHONE, @ADRESSE, @DATE_OUT, @HOUR_OUT, @DATE_IN, @HOUR_IN)"
            .AddWithValue("@ID", SqlDbType.Int).Value = TextBox1.Text
            .AddWithValue("@FIRSTNAME", SqlDbType.NVarChar).Value = TextBox2.Text
            .AddWithValue("@PHONE", SqlDbType.NVarChar).Value = TextBox3.Text
            .AddWithValue("@ADRESSE", SqlDbType.NVarChar).Value = TextBox4.Text
            .AddWithValue("@DATE_OUT", SqlDbType.Date).Value = TextBox5.Text
            .AddWithValue("@HOUR_OUT", SqlDbType.Time).Value = TextBox6.Text
            .AddWithValue("@DATE_IN", SqlDbType.Date).Value = TextBox7.Text
            .AddWithValue("@HOUR_IN", SqlDbType.Time).Value = TextBox8.Text
        End With
        If StrCon.State = ConnectionState.Closed Then StrCon.Open()
        If Command.ExecuteNonQuery() = 1 Then
            MsgBox("SUCCED ADD", MsgBoxStyle.MsgBoxRtlReading, "SUCCES")
        Else
            MsgBox("ERROR FATAL", MsgBoxStyle.MsgBoxRtlReading, "ERROR")
        End If
        StrCon.Close()
    End Using
End Sub

http://www.vbforums.com/showthread.php?862331-Display-record-with-condition-of-date-and-time 和这里 https://www.developpez.net/forums/d1851524/dotnet/langages/vb-net/afficher-records-conditions-date-time/

1 个答案:

答案 0 :(得分:0)

我认为你可能会把等式比较器弄错了。如果您正在寻找过期日期(即过去),则该日期应小于当前日期。

SELECT * 
FROM TABLEOBERGE 
WHERE [DATE_IN] <= CAST(getdate() as Date) AND [HOUR_IN] <= CAST(getDate() AS TIME)

IMO如果您在日期和时间中使用单个字段而不是将其拆分为2,那么您的设计会更好。DateIn类型的DateTime2(7)将非常合适。如果有必要,有许多SQL函数允许您严格按时间或日期进行过滤。它使编写如上所述的查询变得更简单。

SELECT * FROM TABLEOBERGE WHERE [DATE_IN] <= GETDATE()