如何循环遍历字符串数据类型的日期列表,将每个日期传递给sql命令,以将表中的行获取到datagridview中



这是一个函数,用于传递字符串中值在1到12之间的参数month。我有两个日期,一个是月初,另一个是下个月初。我计算这两个日期之间的差异(差(,计算表中日期之间的差(差2(,并将每个差2与差进行比较,以便我只选择同月的日期。然后,我想显示具有我保存在数组中的日期的行,并将其填充到DataTable对象中以放入DataGridView控件中。我一直在填充DataTable对象。

public object monthlyReport(string month)
{
DateTime date = DateTime.Now;
string year = date.ToString("yyyy");
string firstDate, secondDate;
if (month == "12")
{
firstDate = "01/" + month + "/" + year;
secondDate = "01/01/" + (Int32.Parse(year) + 1).ToString();
}
else if (month == "10" || month == "11")
{
firstDate = "01/" + month + "/" + year;
secondDate = "01/" + (Int32.Parse(month) + 1).ToString() + "/" + year;
}
else if (month == "09")
{
firstDate = "01/" + month + "/" + year;
secondDate = "01/10/" + year;
}
else
{
firstDate = "01/" + month + "/" + year;
secondDate = "01/0" + (Int32.Parse(month) + 1).ToString() + "/" + year;
}
//MessageBox.Show(firstDate);
//MessageBox.Show(secondDate);
con.Open();
/*SqlDataAdapter da = new SqlDataAdapter("select * from Rooms where Date between '" + firstDate + "' and '" + secondDate + "'", con);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;*/
SqlCommand cmd = new SqlCommand("select count(Date) from Rooms", con);
int count = Int32.Parse(cmd.ExecuteScalar().ToString());
SqlCommand cmd2 = new SqlCommand("select Date from Rooms", con);
string[] dates = new string[count];
int index = 0;
SqlDataReader dr = cmd2.ExecuteReader();
while (dr.Read())
{
dates[index] = dr.GetString(0);
index++;
}
List<string> newDates = new List<string>();
foreach (string dateItem in dates)
{
TimeSpan difference = Convert.ToDateTime(secondDate) - Convert.ToDateTime(firstDate);
TimeSpan difference2 = Convert.ToDateTime(secondDate) - Convert.ToDateTime(dateItem);
if (difference2.TotalDays < difference.TotalDays)
newDates.Add(dateItem);
}
DataTable dt = new DataTable();
foreach (string dateItem2 in newDates)
{
SqlDataAdapter da = new SqlDataAdapter("select * from Rooms where Date = '" + Convert.ToDateTime(dateItem2).ToString("dd/MM/yyyy") + "'", con);
//da.TableMappings.Add(dt);
//SqlCommand cmd3 = new SqlCommand("select * from Rooms where Date = '" + Convert.ToDateTime(dateItem2).ToString("dd/MM/yyyy") + "'", con);
}

con.Close();
return dt; 
}

或者,如果您只使用了正确的日期-时间类型,您可以使用以下简单代码下载一个月的行:

DataTable dt;
var sql = "SELECT * FROM table WHERE datecolumn BETWEEN @d AND EOMONTH(@d)";
using(var da = new SqlDataAdapter(sql, "CONNECTION STRING")) {
da.SelectCommand.Parameters.Add("@d", SqlDbType.DateTime).Value = new DateTime(2021, 6, 1);
da.Fill(dt);
}

它也被正确地参数化了,所以这种情况不会发生在你身上。。

如果投诉是错过了最后一天有时间的休息日期,你需要意识到,有时间的日期就像带小数的数字,对于任何给定的数字,午夜都是.0——向数据库询问WHERE x BETWEEN 1.0 AND 31.0自然会省略31.5(第31天中午(。在这种情况下,使用WHERE x >= @d AND x < @d2并添加另一个您自己计算的参数,或者如果您希望DB从提供的开始日期计算月末,则使用x < DATEADD(D, 1, EOMONTH(@d))。这样你就可以有效地说";小于32〃;当天捕获31.5

最新更新