How to write DateTimePicker in SQL WHERE statement?

VAer-4038 761 Reputation points
2021-01-13T04:03:01.477+00:00

Take below code for example, how to write correct syntax for sqlDelete? Secondly, AppointmentDate could be Date only (without time), how to make sure comparing Date only (not comparing Time)? Otherwise, data type may be mismatched, so convert both of them to Date only.

Thanks.

using (OdbcConnection Cn = new OdbcConnection(GlobalVariables.DatabaseConnectionString)) 
{

    string sqlDelete = "DELETE FROM TableAppointment WHERE Username = '" + Environment.UserName + "' AND AppointmentDate >= dateTimePickerBegin.Value.Date AND AppointmentDate <= dateTimePickerEnd.Value.Date";


    OdbcCommand cmdDelete = new OdbcCommand(sqlDelete, Cn);
    Cn.Open();

    cmdDelete.ExecuteNonQuery();

}
Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,862 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,458 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,621 Reputation points
    2021-01-13T08:25:08.867+00:00

    Hi VAer-4038,
    You can use "between"operator to select values within a given range in SQL.
    I made a test with the following sql statement and it worked fine.
    And you can modify your "sqlDelete " according to the following sql.
    (The data type of the AppointmentDate field in the Test table is date)

     string sql = "SELECT * FROM test WHERE Name = '" + textBox1.Text + "' And AppointmentDate BETWEEN '" + dateTimePicker1.Value.Date + "' AND '" + dateTimePicker2.Value.Date + "'";  
    

    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments