views:

33

answers:

4

Hello.
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?
Thank you for your help!

A: 

Parameter Size is required for variable size Output parameters. Generally ADO.NET decides the size of the parameter based on the Value assigned to the parameter (hence it is optional), but in output parameter since no value is Set, you need provide the size required for the parameter

Set the Parameter size to size of the output variable from the DB... Say 50

outParam.Size = 50;
The King
It helps. But I don't want to pass any size (I have certain reasons for it).
StuffHappens
If you want to avoid size then all I could think of is to get the result as DataTable / DataSet. But this requires you to change the SP.
The King
A: 

I'm not sure if this is the same problem i've had before, but using a byte for a parameter can sometimes lead to this error.

Try this. Explicitly declare the i parameter as a variable. THEN assign it's value with the Value property.

Harry
+1  A: 

VarChar and NVarChar are variable width character fields (thus var+char). You have to set the length, otherwise the default is zero.

Sachin Shanbhag
What if I supply the size = 1000 for int? Will I get an exception?
StuffHappens
@StuffHappens - The varchar and NVarchar always adjust to the data length no matter what size you give. So you can set any size (MAX 4000 for Nvarchar and 8000 for varchar). It wont hurt.
Sachin Shanbhag
Just to add that if you assign a value to the parameter, the size of that value will be used as the default instead of 0 (i.e. you can omit the size).
AdaTheDev
+1  A: 

Check MSDN : SqlParameter.Size Property

For bidirectional and output parameters, and return values, you must set the value of Size. This is not required for input parameters, and if not explicitly set, the value is inferred from the actual size of the specified parameter when a parameterized statement is executed.

Pranay Rana