FAQ Item: Why I cannot pass 0 as value to a SQL parameter in ADO.NET? RRS feed

  • Question

  • Why not be able to pass 0 as value to a SQL parameter in ADO.NET?
    Sunday, June 20, 2010 1:37 PM


  • When we add parameters to SqlCommand Object, and if the parameter value is 0(zero), it is treated as parameter has not been assigned any value (may be null) and after command.ExecuteReader() statement, .NET throws an exception saying the parameter was not specified.

    The solution:

    When you specify an Object in the value parameter, the SqlDbType is inferred from the Microsoft .NET Framework type of the Object.

    Use caution when you use this overload of the SqlParameter constructor to specify integer parameter values. Because this overload takes a value of type Object, you must convert the integral value to an Object type when the value is zero, as the following C# example demonstrates.

    Parameter = new SqlParameter("@pname", Convert.ToInt32(0));

    If you do not perform this conversion, the compiler assumes that you are trying to call the SqlParameter (string, SqlDbType) constructor overload.


    Related Threads:


    • Marked as answer by MSDN FAQ Sunday, June 20, 2010 1:38 PM
    Sunday, June 20, 2010 1:38 PM