0

I get this error when I compare to dates.

sql query command : Select * from processTBL WHERE is=2016144 and date between '10/06/2016' and '15/06/2016' that command work but when Fill Data to DateTabe I get converting error.

That's my c# method;

public DataGridView hesapOzeti(string command)
    {
        DataGridView gdview = new DataGridView();

        if (connection.State == ConnectionState.Closed)
            connection.Open();
        SqlCommand komut = new SqlCommand(command, connection);
        SqlDataAdapter da = new SqlDataAdapter(komut);
        DataTable dt = new DataTable();
        da.Fill(dt);
        connection.Close();
        gdview.DataSource = dt;
        return gdview;
    }

The Error:

enter image description here

1

2 Answers 2

1

A quick fix would be to send dates in an unambiguous format, so that your format is properly interpreted:

Select * from processTBL WHERE is=2016144 and date between '20160601' and '20160616'

The error comes from the fact that 15 is considered a month and thus the date is unparsable.

The correct way of doing it is to use a parameterized query:

command.Parameters.AddWithValue("@is", 2016144);
command.Parameters.AddWithValue("@FromDate", new DateTime(2016, 06, 10));    
command.Parameters.AddWithValue("@ToDate", new DateTime(2016, 06, 15));  

Your query becomes:

Select * from processTBL WHERE is = @is and date between @FromDate and @ToDate

Generally speaking, you should always try to use parameterized queries to avoid such errors and protect against SQL injection.

Sign up to request clarification or add additional context in comments.

2 Comments

Go all the way and parameterize the is as well. Also, read Can we stop using AddWithValue() already?
Thanks bro it is work I change this command.Parameters.AddWithValue("@FromDate", DateTime.Parse(fromDate))
0

The date format for literals is dependant upon the locale (specifically the DATEFORMAT). The BOL page for datetime lists the locale and non-locale specific formats

https://msdn.microsoft.com/en-AU/library/ms187819.aspx

Ideally, you should use the ISO 8601 format - YYYY-MM-DDThh:mm:ss[.mmm] or YYYYMMDD[ hh:mm:ss[.mmm]]

In your code, try date between '20160610' and '20160615'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.