使用日历选择两个日期之间的所有记录

时间:2014-01-21 14:14:45

标签: c# sql

我想按两个日期搜索记录,这两个日期将由用户通过日历选择。这就是我编写查询的方式:

public List<Staff> GetStaff(DateTime DateOne, DateTime DateTwo, string staffColourCode)
{
    List<Staff> l= new List<Staff>();
    SqlConnection conn = new connection etc...
    SqlCommand command = new SqlCommand("SELECT * FROM TableName WHERE CAST(Time AS date) BETWEEN @Time and @Time", conn);
    command.Parameters.AddWithValue("@Time", DateOne);


    conn.Open();
    SqlDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
        Staff s= new Staff();
        s.Name= reader["Name"].ToString();
        etc...

        l.Add(s);
    }
    conn.Close();
    return l;
}

在我的数据库中,如果我用一些日期替换时间然后它可以工作,但我如何编写一个允许用户选择两个日期的查询,并基于DateOne和DateTwo搜索具有任何颜色代码的工作人员列表用户选择例如绿色,黄色等...

2 个答案:

答案 0 :(得分:2)

您需要两个不同的参数:

SqlCommand command = new SqlCommand("SELECT * FROM TableName " + 
                                    "WHERE CAST(Time AS date) BETWEEN @DateOne and @DateTwo", conn);
command.Parameters.AddWithValue("@DateOne", DateOne);
command.Parameters.AddWithValue("@DateTwo", DateTwo);

答案 1 :(得分:0)

如上面的评论所述,您只使用了一个参数

public List<Staff> GetStaff(DateTime DateOne, DateTime DateTwo,string color)
{
    //Some connection stuff
    SqlCommand command = new SqlCommand(@"SELECT * FROM TableName 
                                          WHERE CAST(Time AS date)> @Time 
                                          and CAST(Time AS date)< @Time2
                                          and staffColorCode = @color", conn);
    command.Parameters.AddWithValue("Time", DateOne);
    command.Parameters.AddWithValue("Time2", DateTwo);
    command.Parameters.AddWithValue("color", color);

    //retrieve data
}

添加了额外参数