You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SqlCommand AddWithValue调用存储过程报错:未提供@ID参数

问题排查:存储过程提示@ID参数未提供,但已添加参数

我的GridView行更新事件代码

protected void gridOmniZone_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    GridViewRow row = gridOmniZone.Rows[e.RowIndex];
    Int64 ID = Convert.ToInt64(gridOmniZone.DataKeys[e.RowIndex].Values[0]);
    string Description = (row.Cells[2].Controls[1] as TextBox).Text;
    string LatCenter = (row.Cells[3].Controls[1] as TextBox).Text;
    string LongCenter = (row.Cells[4].Controls[1] as TextBox).Text;
    string Radius = (row.Cells[5].Controls[1] as TextBox).Text;
    string Address = (row.Cells[6].Controls[1] as TextBox).Text;
    string City = (row.Cells[7].Controls[1] as TextBox).Text;
    string State = (row.Cells[8].Controls[1] as TextBox).Text;
    string PostalCode = (row.Cells[9].Controls[1] as TextBox).Text;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("dbo.usp_UpdateOmniZone"))
        {
            cmd.Connection = con;
            cmd.Parameters.Add("@ID", SqlDbType.BigInt);
            cmd.Parameters[0].Value = ID;
            cmd.Parameters.AddWithValue("@Description", Description);
            cmd.Parameters.AddWithValue("@LatCenter", LatCenter);
            cmd.Parameters.AddWithValue("@LongCenter", LongCenter);
            cmd.Parameters.AddWithValue("@Radius", Radius);
            cmd.Parameters.AddWithValue("@Address", Address);
            cmd.Parameters.AddWithValue("@City", City);
            cmd.Parameters.AddWithValue("@State", State);
            cmd.Parameters.AddWithValue("@PostalCode", PostalCode);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
    gridOmniZone.EditIndex = -1;
    this.BindGrid();
}

执行时抛出的错误

stored procedure expects parameter @ID which was not supplied.
(翻译:存储过程期望参数@ID,但未提供)

调试确认变量ID是有效的整数值,且已添加@ID参数,问题出在哪里?


问题原因与解决方法

核心问题是未设置SqlCommand的CommandType为StoredProcedure。默认情况下CommandType的值是Text,此时SQL Server会把"dbo.usp_UpdateOmniZone"当作普通SQL语句执行,而非调用存储过程,导致你添加的参数无法被存储过程识别。

只需在创建SqlCommand后添加一行代码即可修复:

cmd.CommandType = CommandType.StoredProcedure;

修正后的关键代码段:

using (SqlCommand cmd = new SqlCommand("dbo.usp_UpdateOmniZone"))
{
    cmd.Connection = con;
    // 新增此行,明确指定调用的是存储过程
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@ID", SqlDbType.BigInt);
    cmd.Parameters[0].Value = ID;
    // 后续参数添加代码保持不变...
}

设置后SQL Server会正确识别操作类型,将你添加的参数绑定到存储过程的对应参数上,错误即可消除。


内容的提问来源于stack exchange,提问作者user5125988

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 17:57:52