Problem in C# code behind and with SQL string date and the Between statement

Last post 05-13-2008 9:29 AM by doyleits. 1 replies.

Sort Posts:

  • Problem in C# code behind and with SQL string date and the Between statement

    05-13-2008, 8:31 AM
    • Loading...
    • jyllan
    • Joined on 01-15-2008, 2:04 PM
    • Posts 76

    Hi

    I have a problem to search between two dates, if I use Convert(varchar(10),ContactCreateDate,105) in a single textbow and for a single search date it is okay, but when I use the Convert(varchar(10),ContactCreateDate,105) against two textboxes it did't function.

    Can anybody help me ?

    MY code

    if (TBContactSearchDateStart.Text.Length > 0 && TBContactSearchDateEnd.Text.Length > 0)

    {

    strWhere += " AND Convert(varchar(10),ContactCreateDate,105) BETWEEN '%" + TBContactSearchDateStart.Text + "%' AND '%" + TBContactSearchDateEnd.Text + "%'";

  • Re: Problem in C# code behind and with SQL string date and the Between statement

    05-13-2008, 9:29 AM
    Answer
    • Loading...
    • doyleits
    • Joined on 09-21-2007, 5:58 PM
    • Fort Worth, TX
    • Posts 468

    I would highly recommend using a parameterized query, but for the sake of correcting your example, see the code below. You do not need to convert your source column to a varchar for the comparison to work - SQL Server will convert the date strings to datetime

     

    // Declare date variables
    DateTime startDate, endDate;
    
    // Try parsing each date (avoids exceptions)
    DateTime.TryParse(
        TBContactSearchDateStart.Text, 
        System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat, 
        Globalization.DateTimeStyles.None, 
        out startDate);
    DateTime.TryParse(
        TBContactSearchDateEnd.Text, 
        System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat, 
        Globalization.DateTimeStyles.None, 
        out endDate);
    
    if (startDate > DateTime.MinValue && endDate > DateTime.MinValue)
    {
        // Save query time by NOT converting the source column
        strWhere += "AND ContactCreateDate BETWEEN '" +
            startDate.ToShortDateString() + "' AND '" +
            endDate.ToShortDateString() + "'";
    }
     
    Mark Doyle
    Doyle ITS
    www.doyleits.com
Page 1 of 1 (2 items)
Microsoft Communities
Page view counter