简体   繁体   中英

Stored procedure expects parameter though parameter is provided

I am using VS 2015 and SQL Server 2016.

In my C# code, I am assigning the parameters which my stored procedure expects, but am getting an error as my stored procedure is expecting a parameter.

My stored procedure:

CREATE PROCEDURE [dbo].[SDDeleteTAR]
    @TARKey int
AS
BEGIN
    DELETE technical_assistance_requests  
    WHERE request_id = @TARKey
END

My C# code:

Label id = (Label)e.Item.FindControl("REQUEST_ID");
var x = id.Text;
int rid = Convert.ToInt32(x);

string cs = ConfigurationManager.AppSettings.Get("connectionString").ToString();

using (SqlConnection con = new SqlConnection(cs))
{
    SqlCommand cmd = new SqlCommand("SDDeleteTAR", con);
    cmd.CommandType = CommandType.StoredProcedure; 
    cmd.Parameters.AddWithValue("@RequestID", rid); 

    con.Open();
    cmd.ExecuteNonQuery(); 
}

When I run this, I get this error:

Procedure or function 'SDDeleteTAR' expects parameter '@TARKey', which was not supplied.

I am passing the required parameters and executing my command type as CommandType.StoredProcedure , and am not able to resolve this.

I also checked the same issue in StackOverflow here but the submitter is missing the command type declaration.

Any help is appreciated, in pointing out where I am going wrong.

You should change @RequestID to @TARKey . Because your stored procedure expects a parameter with that name.

You can safely execute a stored procedure without directly specifying the names, by using SqlCommandBuilder.DeriveParameters . This will retrieve the parameters from the server and create the SQLParameter collection for you.

SqlCommand cmd = new SqlCommand("SDDeleteTAR", con);
SqlCommandBuilder.DeriveParameters(cmd);
cmd.Parameters[0].Value = rid;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM