asp.net在一个GridView中有多个sqlcommands

时间:2016-03-15 17:29:43

标签: asp.net gridview sqlcommand

我有问题在一个GridView中显示多个sql命令。也许我不需要从两个表中显示两个sqlcommands但我不知道该怎么做。 第一个命令是让所有在两个日期之间休假的员工。 第二个命令我用它来按ID检索日期。但我不知道如何将它们绑定到一个GridView以显示为附加图像。提前谢谢。

我现在得到的是什么 阿尔伯特2016-03-16
Albert 2016-03-17

阿尔伯特2016-03-18
约翰娜2016-03-17

约翰娜2016-03-18
Eric 2016-03-18

而不是
Albert 2016-03-16,2016-03-17,2016-03-18
约翰娜2016-03-17,2016-03-18
Eric 2016-03-18
我想我必须在两个while语句之间循环,也许用一个sqlcommand?
enter image description here

我的代码是:

    using (SqlConnection con = new SqlConnection(connection))
{
 con.Open();
 SqlCommand cmd = new SqlCommand(" SELECT distinct E.EmployeeId, E.FirstName  
 FROM Employee E INNER JOIN Vacation V ON E.EmployeeId = V.EmployeeId " +
  " WHERE ((V.Dates >= @Start AND V.Dates <= @End) ) ", con);
  cmd.Parameters.AddWithValue("@Start", (Calendar1.SelectedDates[0]).Date.ToShortDateString());
 cmd.Parameters.AddWithValue("@End", (Calendar1.SelectedDates[Calendar1.SelectedDates.Count - 1]).Date.ToShortDateString());
using (SqlDataReader dr = cmd.ExecuteReader())
 {
   while (dr.Read())
    {

 Response.Write((dr[1]).ToString() + "  "); // Cheack if retrivs Employeename
 // Now By Id I want to get all dates belong to specifik employee

SqlCommand cmd2 = new SqlCommand(" SELECT V.Dates FROM Vacation V " +
" WHERE ((V.Dates >= @Start AND V.Dates <= @End) ) ", con);
cmd2.Parameters.AddWithValue("@Start", (Calendar1.SelectedDates[0]).Date.ToShortDateString());
cmd2.Parameters.AddWithValue("@End", (Calendar1.SelectedDates[Calendar1.SelectedDates.Count - 1]).Date.ToShortDateString());
cmd2.Parameters.AddWithValue("@EmployeeId", Convert.ToInt32(dr[0]));                                    
using (SqlDataReader dr2 = cmd2.ExecuteReader())
{
 while (dr2.Read())
    {
    //Response.Write(Convert.ToDateTime(dr2[0]));
     GridView7.DataSource = cmd2.ExecuteReader();
GridView7.DataBind();
    }

   }
       Response.Write("<br/>");
 } 


  }
    con.close();
}
GridView7.DataSource = cmd.ExecuteReader();
GridView7.DataBind();

1 个答案:

答案 0 :(得分:0)

FOR XML PATH语法允许您的查询将多个值组合在一个中:

SELECT 
    E.EmployeeId, 
    E.FirstName,
    REPLACE(STUFF((
        SELECT 
            COALESCE('¶' + V.Dates, '')
        FROM 
            Vacation V 
        WHERE 
            V.EmployeeId = E.EmployeeId AND V.Dates >= @Start AND V.Dates <= @End
        FOR XML PATH('')), 1, 1, ''), '¶', ', ') AS VacationDates
FROM 
    Employee E

如果需要,您可以用其他内容替换', '分隔符。

注意:抱歉进行多重编辑。我只是不确定你如何联系员工,假期和约会。这段代码基本上显示了FOR XML PATH语法的想法。