如何在ASP.NET中使用JOIN SQL语句

时间:2016-06-08 22:04:42

标签: c# sql asp.net sql-server

好的,所以我是一名头疼的编程学生,希望有人能够治愈。

我目前正在Microsoft Visual Studio中为项目创建一个使用ASP.NET的网站,这是我的问题:

我真的不知道如何组合来自两组数据的数据。

以下是两个表的表结构:

LeaveCategory

Id 是LeaveCategory的主键。

LeaveCategory的数据

LeaveType

ID 是主键, LeaveCategoryId 是LeaveType的外键。

LeaveType数据

输出:

Leave Type ACL1 from LeaveType ----> Category AL from LeaveCategory
Leave Type ACL2 from LeaveType ----> Category AL from LeaveCategory
Leave Type ACL3 from LeaveType ----> Category AL from LeaveCategory
Leave Type ACL4 from LeaveType ----> Category AL from LeaveCategory
Leave Type OPL from LeaveType -----> Category ML from LeaveCategory
Leave Type HPL from LeaveType -----> Category ML from LeaveCategory
Leave Type CGL from LeaveType -----> Category UL from LeaveCategory
Leave Type MGL from LeaveType -----> Category UL from LeaveCategory
Leave Type SDL from LeaveType -----> Category ML from LeaveCategory

.aspx页面需要使用JOIN sql语句从两个表中检索。但我真的不知道如何打字:((

所以这是我的代码:

SqlConnection conn = null;
SqlCommand cmd = null;
string connectionString = null;
protected void Page_Load(object sender, EventArgs e)
{
    SqlDataReader dr = null;

    connectionString = ConfigurationManager.ConnectionStrings["LeaveManagementCS"].ConnectionString;

    string sql = "SELECT * FROM LeaveType";

    try
    {
        conn = new SqlConnection(connectionString);

        cmd = new SqlCommand(sql, conn);

        conn.Open();

        dr = cmd.ExecuteReader();

        lblOutput.Text = "<table Border='1'>";
        lblOutput.Text += "<tr><th>Id </th><th>Leave Type</th><th>Description</th><th>Number of Days</th></tr>";

        while (dr.Read())
        {
            string id = dr["Id"].ToString();

            string type = dr["Type"].ToString();

            string desc = dr["Description"].ToString();

            string nod = dr["NumofDays"].ToString();

            lblOutput.Text += "<tr><td>" + id + "</td>";
            lblOutput.Text += "<td>" + type + "</td>";
            lblOutput.Text += "<td>" + desc + "</td>";
            lblOutput.Text += "<td>" + nod + "</td></tr>";
        }
        dr.Close();

        lblOutput.Text += "</table>";
    }
    catch (Exception ex)
    {
        lblOutput.Text = "Error Message" + ex.Message;
    }
    finally
    {
        if (conn != null)
            conn.Close();
    }
}

1 个答案:

答案 0 :(得分:1)

我首先要说的是,构建此页面的方式非常脆弱,容易出错和出错。我不建议在实际的业务情况下这样做。出于演示目的,在教育背景下,我认为这是可以接受的。话虽如此,这是获取您要求的数据的SQL。

string sql = @"
SELECT 
  LT.Id,
  LT.Type,
  LT.Description,
  LT.NumofDays,
  LC.Description CategoryDescription
FROM 
  LeaveType LT
  JOIN LeaveCategory LC
    ON LT.LeaveCategoryId = LC.Id";