简体   繁体   English

带文本框的两个日期之间的SQL查询

[英]Sql query between two dates with textboxes

I have a query that gets data from my database and it needs to filter out data between certain dates that the user will fill in two textboxes. 我有一个查询,该查询从数据库中获取数据,它需要过滤掉用户将填写两个文本框的某些日期之间的数据。 I need to fill in the textboxes like: 2016-9-13 otherwise it wont work (the date in the database is also 2016-9-13). 我需要填写以下文本框:2016-9-13,否则它将无法正常工作(数据库中的日期也是2016-9-13)。 But when it fills the gridview the cell says: 13-9-2016. 但是当它填满gridview时,单元格会说:13-9-2016。

I want to fill in the dates in the order like: 13-9-2016. 我想按以下顺序填写日期:13-9-2016。 How can i do this and what do i need to change? 我该怎么做,我需要改变什么?

Here is some code that gives me the data from the database. 这是一些代码,这些代码为我提供了数据库中的数据。

 connect = new SqlConnection(@"Data Source=LP12;Initial Catalog=Data;Integrated Security=True");
        connect.Open();

        SqlCommand cmd = new SqlCommand();
        cmd.Connection = connect;
        cmd.CommandText = "SELECT DrukSensor, FlowSensor, TempSensor, KwaliteitSensor, OlieVerbruik, Toerental, DateTime, Schip FROM SysteemSensorInfo WHERE DateTime BETWEEN @StartDate AND @EndDate";

        cmd.Parameters.AddWithValue("@StartDate", TextBoxBeginDatum.Text);
        cmd.Parameters.AddWithValue("@EndDate", TextBoxEindDatum.Text);
        DataSet ds = new DataSet();
        new SqlDataAdapter(cmd).Fill(ds);
        GridView1.DataSource = ds.Tables[0];
        GridView1.DataBind();

Basically, parse the dates and pass down DateTime values: 基本上,解析日期并传递DateTime值:

cmd.Parameters.AddWithValue("@StartDate", ParseDate(TextBoxBeginDatum.Text));
cmd.Parameters.AddWithValue("@EndDate", ParseDate(TextBoxEindDatum.Text));

...

static DateTime ParseDate(string text) {
    // TODO; possibly just: return DateTime.Parse(text);
}

You should use Datediff() function. 您应该使用Datediff()函数。 Internally, It will manage valid date in any format for dates comparison. 在内部,它将以任何格式管理有效日期以进行日期比较。

"SELECT DrukSensor, FlowSensor, TempSensor, KwaliteitSensor, OlieVerbruik,     Toerental, DateTime, Schip 
FROM SysteemSensorInfo 
WHERE datediff(day,DateTime,@StartDate)<=0 AND datediff(day,DateTime,@EndDate)>=0"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM