简体   繁体   中英

Adding integer parameter to stored procedure in ASP.NET C#

While trying to pass an integer parameter @id to a stored procedure, I get an error da.Fill(ds) :

Additional information: Conversion failed when converting the varchar value '@id' to data type int.

I have made sure that integer value is passed and stored procedure contain the correct datatype. What other possibilities are there to rectify this error?

SqlConnection conn = new SqlConnection(cs);
conn.Open(); 

SqlCommand cmd1 = new SqlCommand("asp_GetTrainingDetail", conn);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("@id", id);

SqlDataAdapter da = new SqlDataAdapter(cmd1);
DataSet ds = new DataSet();
da.Fill(ds);

Try this...

 SqlConnection conn = new SqlConnection(cs);
        conn.Open(); SqlCommand cmd1 = new 
        SqlCommand("asp_GetTrainingDetail", conn);
        cmd1.CommandType = CommandType.StoredProcedure;
        cmd1.Parameters.AddWithValue("@id", Int.Parse(id));
        SqlDataAdapter da = new SqlDataAdapter(cmd1);
        DataSet ds = new DataSet();
        da.Fill(ds);

If you know better, do not use AddWithValue() ... it has to "guess" what datatype you have in your DB based on what you put into the command. It is errorprone and causes unneeded conversions to take place.

Also: use using(..) around disposables, especially when using Database-access as it will close your connections even if exceptions arise - not using using might let some connection stay unclosed.

DataSet ds = new DataSet ();
using (var conn = new SqlConnection (cs))
{
    using (var cmd1 = new SqlCommand ("asp_GetTrainingDetail", conn))
    {
        cmd1.CommandType = CommandType.StoredProcedure;
        cmd1.Parameters.Add("@id", System.Data.SqlDbType.BigInt).Value = id;

        using (var da = new SqlDataAdapter (cmd1))
        {
            da.Fill (ds);
        }
    }
}

Read the link in do not use AddWithValue() for more background infos.

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