【问题标题】:C# & SQL Server query error: The multi-part identifier cannot be boundC# & SQL Server 查询错误:无法绑定多部分标识符
【发布时间】:2016-07-12 08:53:58
【问题描述】:
protected void btnSubmit_Click(object sender, EventArgs e)
{
    connectionString = ConfigurationManager.ConnectionStrings["LeaveMangementSystemCS"].ConnectionString;
    conn = new SqlConnection(connectionString);
    string sql = "UPDATE LeaveType  SET LeaveType.Type=@Type, LeaveType.Description=@Description, LeaveType.NumOfDays=@NumOfDays, LeaveCategory.Category=@Category FROM LeaveType INNER JOIN LeaveCategory on LeaveType.LeaveCategoryId = LeaveCategory.Id  WHERE LeaveType.Id=@id";

    try
    {
            cmd = new SqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("@Type", tbType.Text);
            cmd.Parameters.AddWithValue("@Description", tbDescription.Text);
            cmd.Parameters.AddWithValue("@NumOfDays",tbNumOfDays.Text);
            cmd.Parameters.AddWithValue("@Category", ddlLeaveCategory.Text);
            cmd.Parameters.AddWithValue("@id", lblIdOut.Text);

            conn.Open();
            int rows = cmd.ExecuteNonQuery();

            if (rows > 0)
            {
                lblOutput.Text = " Updated successfully.";
            }
    }
    catch (Exception ex)
    {
        lblOutput.Text = "Error Message : " + ex.Message;
    }
    finally
    {
        if (conn != null)
            conn.Close();
    }
}

我的 SQL 查询出错:

无法绑定多部分标识符“LeaveCategory.Category”。

我曾尝试将 leavetype 用作 a 并将 leavecategory 用作 b 但仍然出现此错误。

【问题讨论】:

标签: c# sql sql-server


【解决方案1】:

您不能在一个语句中更新多个表!查看您的 sql 变量:

UPDATE LeaveType  
SET LeaveType.Type=@Type
,   LeaveType.Description=@Description
,   LeaveType.NumOfDays=@NumOfDays
,   LeaveCategory.Category=@Category 
FROM LeaveType 
INNER JOIN LeaveCategory on LeaveType.LeaveCategoryId = LeaveCategory.Id  
WHERE LeaveType.Id=@id";

在这里您尝试更新表 LeaveType 和表 LeaveCategory 中的一列

请看thisasnwer

【讨论】:

  • 我也试过了,但是在我尝试更新html中的状态后,我的表格不会更新。
  • 什么意思?我们是在谈论 SQL 还是 HTML????在问题中,我没有看到任何有关 HTML 的信息!
  • 我的意思是这段代码在我的 aspx.cs 文件下,使用 c# microsoft visual studio 中的母版页,我启动到 chrome 并尝试更新错误显示的位置 多部分标识符“LeaveCategory.Category”无法绑定。
  • 你明白答案了吗?我写道,您不能按原样使用您的 sql 变量。您应该单击“请参阅此答案”链接,然后阅读可能的解决方案并将其用于您的查询。在 asnwer 中,我刚刚显示了您的 sql 变量的值,但使用格式来显示问题所在
【解决方案2】:

需要准备两条单独的sql语句,不能一次更新两张表。您可以将它们包装在存储过程中,一个接一个地更新它们,然后从 C# 代码中调用 proc。

【讨论】:

  • 可能(通常是,如果您“同时”更新它们)很好的理由也将它们包装在事务中。
猜你喜欢
  • 1970-01-01
  • 2022-11-19
  • 1970-01-01
  • 1970-01-01
  • 2020-06-16
  • 1970-01-01
  • 1970-01-01
  • 2011-10-12
  • 1970-01-01
相关资源
最近更新 更多