【问题标题】:Stored procedure expects parameter id value which is not supplied存储过程需要未提供的参数 id 值
【发布时间】:2021-07-14 04:03:21
【问题描述】:

我有一张带列的学生表

id primary key, firstname, lastname, birthdate, gender, phone, address. 

我正在使用 ASP.NET 中的 WebForms。

我有这个存储过程。

create procedure spAddStudents
(
    @id int
    , @firstname nvarchar(50)
    , @lastname nvarchar(50)
    , @birthdate date
    , @gender nvarchar(5)
    , @phone nvarchar(50)
    , @address nvarchar(200)  
)  
as  
Begin  
    insert into students
    values (@id, @firstname, @lastname, @birthdate, @gender, @phone, @address)  
End

在网络表单中我写了这段代码

SqlCommand cmd = new SqlCommand("spAddStudents",con);
cmd.Parameters.AddWithValue("@id",txtId.Text);
cmd.Parameters.AddWithValue("@firstname",txtFirstName.Text);
cmd.Parameters.AddWithValue("@lastname",txtLastName.Text);
cmd.Parameters.AddWithValue("@birthdate",txtBirthDate.Text);
cmd.Parameters.AddWithValue("@gender",ddlGender.SelectedValue);
cmd.Parameters.AddWithValue("@phone",txtPhone.Text);
cmd.Parameters.AddWithValue("@address",txtAddress.Text);

con.Open();
int k = cmd.ExecuteNonQuery();
if (k != 0)
{
    lblMessage.Text = "Record inserted successfully";
}

在点击添加按钮时用数据填充表单后,它应该将数据添加到表中,但它给了我错误提示:

存储过程需要未提供的参数 id 值。

我尝试将 id 设为自动增量值。并从表单中删除了 id 字段。这次当我按下添加按钮时,它表示存储过程期望未提供名字的值。

错在哪里?

谢谢。

【问题讨论】:

  • 嗨@LMS,建议不要使用 .AddWithValue() 作为您为@id 传入的存储过程和SqlParameter 中的数据类型不匹配。您可以阅读此article。谢谢。
  • 还有更多的最佳实践,不要在你的 SP 前面加上 sp。而且您应该始终列出要插入的列。您需要在 Execute 命令上暂停调试器并检查您的参数值(在删除 AddWithValue 之后)。
  • 在 c# 中,您将所有变量转换为文本。如果它们来自文本框,则执行以下操作: int.Parse(txtId.Text)

标签: c# asp.net sql-server


【解决方案1】:

可能是存储过程中的插入命令缺少id。

如前所述,您最好在此处使用强类型转换。

如上所述,paramaters.Add 是首选。

using (SqlCommand cmd = new SqlCommand("spAddStudents", con))
{
    cmd.Parameters.Add("@id", SqlDbType.Int).Value = txtId.Text;
    cmd.Parameters.Add("@firstname", SqlDbType.NVarChar).Value = txtFirstName.Text;
    . etc .etc .etc

    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Connection.Open();
    cmd.ExecuteNonQuery();
}

请注意我们是如何强制命令类型的 - 或许可以尝试一下。我认为问题出在存储过程代码中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-27
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    • 2017-09-15
    相关资源
    最近更新 更多