ADO.NET - The Size property has an invalid size of 0

Viewed 64110

I'm trying to get output value from DB via ADO.NET. There's a client code:

    using (var connection = new SqlConnection(ConnectionString))
    {
        connection.Open();
        SqlCommand command = new SqlCommand("pDoSomethingParamsRes", connection);
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add("@i", 1);
        var outParam = new SqlParameter("@out", SqlDbType.VarChar);
        outParam.Direction = ParameterDirection.Output;
        command.Parameters.Add(outParam);
        command.ExecuteNonQuery();
        Console.WriteLine(command.Parameters["@out"].Value.ToString());
    }

When I run this I get the following exception:

the Size property has an invalid size of 0

According to manual SqlParameter.Size Property I might omit size. Why do I get this exception?

How to make it work without passing size?

10 Answers

Incidentally, setting the size property of an output parameter is necessary even if it isn't a string-type parameter. For example, if you are using a System.Data.SqlDbType.Int, you should set the size to be 4.

you have to set Size for parameter output

using (var connection = new SqlConnection(ConnectionString))
{
    connection.Open();
    SqlCommand command = new SqlCommand("pDoSomethingParamsRes", connection);
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.Add("@i", 1);
    var outParam = new SqlParameter("@out", SqlDbType.VarChar);
    outParam.Direction = ParameterDirection.Output;
    outParam.Size = 50; // this is example
    command.Parameters.Add(outParam);
    command.ExecuteNonQuery();
    Console.WriteLine(command.Parameters["@out"].Value.ToString());
}

I had the same error and below is my code that works

cmd.Parameters("@ProjectKey").SqlDbType = SqlDbType.NVarChar
cmd.Parameters("@ProjectKey").Size = 150
cmd.Parameters("@ProjectKey").Direction = ParameterDirection.InputOutput
cmd.ExecuteNonQuery()
Related