Pergunta

The following query doesn't return any results when I try to select records between February and March.

Here is the query that I'm using :

SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM data WHERE  CONVERT(VARCHAR(50),data,105) BETWEEN  CONVERT(VARCHAR(50),'" + dateTimePicker1.Text + "',105) AND CONVERT(VARCHAR(50),'"+dateTimePicker3.Text+"',105)", conn);
  • data is type VARCHAR(50) and i want to convert it to dd-MM-yyyy format
Foi útil?

Solução

Your SQL should be something like

 SELECT * FROM data 
 WHERE  CONVERT(datetime, data, 105)  >= CONVERT(datetime, '01-01-2014', 105) 
     AND  CONVERT(datetime, data, 105) <= CONVERT(datetime, '01-31-2014', 105)

Outras dicas

I would use date value from DatePicker Once you convert everything to Date SQL will not have problem of comparing mm-dd-yyyy to dd-mm-yyyy

SELECT * 
FROM MyTable
WHERE CONVERT(DATE,MyStringDate,105) >= dateTimePicker1.Value.Date
AND CONVERT(DATE,MyStringDate,105) <= dateTimePicker.Value.Date

You are doing too many conversions. SQL will have a hard time determining BETWEEN on VARCHAR types.

Instead convert things to DATE or DATETIME (depending on your SQL Server Version and type)

Also you should use parameterized queries to avoid SQL Injection.

Something like this would work well:

using (var da = new SqlDataAdapter())
{
    da.SelectCommand.CommandText = 
         "SELECT * FROM data WHERE CONVERT(datetime, data, 105) >= @Date1 AND CONVERT(datetime, data, 105) <= @Date2";
    //Use the DateTimePicker's Value property here, not the Text Property
    da.SelectCommand.Parameters.AddWithValue("@Date1", dateTimePicker1.Value);
    da.SelectCommand.Parameters.AddWithValue("@Date2", dateTimePicker3.Value);
    da.Fill(yourDataTable); //Or whatever you're doing
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top