我正在尝试将日期解析为SQL,但是该命令似乎忽略了参数:
private void updateTasksDGV(DateTime? start, DateTime? end)
{
if (start == null)
{
string query = "select * from CRS_Diary where cast(EndDate as date) <= convert(date,GETDATE()) and Complete = 0";
dgvTasks.DataSource = GetTable(query);
return;
}
try
{
using (SqlConnection connection = getSQlCon())
{
using (SqlCommand cmd = new SqlCommand(@"Select * from crs_diary where enddate between @Start and @End and complete = 0", connection))
{
MessageBox.Show("made it to conn " + start.ToString() + " - " + end.ToString());
cmd.CommandType = CommandType.Text;
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "@Start";
parameter.SqlDbType = SqlDbType.DateTime;
parameter.Direction = ParameterDirection.Input;
parameter.Value = start;
SqlParameter parameter2 = new SqlParameter();
parameter2.ParameterName = "@End";
parameter2.SqlDbType = SqlDbType.DateTime;
parameter2.Direction = ParameterDirection.Input;
parameter2.Value = end;
cmd.Parameters.Add(parameter);
cmd.Parameters.Add(parameter2);
//cmd.Parameters.AddWithValue("@Start", SqlDbType.DateTime).Value = start.Value;
//cmd.Parameters.AddWithValue("@End", SqlDbType.DateTime).Value = end.Value;
connection.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.Clipboard.SetText(cmd.CommandText.ToString());
}
}
}
catch (System.Data.DataException ex)
{
MessageBox.Show(ex.Message);
}
}
我可以使它使用commandtype存储过程传递参数,但是在这种情况下,我不希望这样做。输出/ DGV没有执行任何操作。
答案 0 :(得分:0)
您应该使用ExecuteReader而不是ExecuteNonQuery。还要注意,对于SQL Server,您不应将BETWEEN用于日期范围,而应使用> =和<。稍微修改了代码:
private void updateTasksDGV(DateTime? start, DateTime? end)
{
if (!end.HasValue)
{
end = DateTime.MaxValue;
}
if (!start.HasValue)
{
string query = "select *
from CRS_Diary
where EndDate <= GETDATE() and Complete = 0";
dgvTasks.DataSource = GetTable(query);
return;
}
try
{
DataTable tbl = new DataTable();
using (SqlConnection connection = getSQlCon())
{
using (SqlCommand cmd = new SqlCommand(@"Select * from crs_diary
where enddate >= @Start and endDate < @End and complete = 0", connection))
{
MessageBox.Show("made it to conn " + start.ToString() + " - " + end.ToString());
cmd.Parameters.Add(new SqlParameter("@Start", SqlDbType.DateTime));
cmd.Parameters.Add(new SqlParameter("@End", SqlDbType.DateTime));
cmd.Parameters["@Start"].Value = start;
cmd.Parameters["@End"].Value = end;
connection.Open();
tbl.Load(cmd.ExecuteReader());
System.Windows.Forms.Clipboard.SetText(cmd.CommandText.ToString());
}
}
dgvTasks.DataSource = null;
dgvTasks.DataSource = tbl;
}
catch (System.Data.DataException ex)
{
MessageBox.Show(ex.Message);
}
}
请注意,如果您要查询2018年7月的数据,则开始日期为:2018/7/1,结束日期为2018/8/1(排除的最短日期时间)。