75

I am working on a social network, one of my procedures returns a VARCHAR output. So this is what I wrote:

SqlParameter job1 = cmd2.Parameters.Add("@job", SqlDbType.VarChar);
job1.Direction = ParameterDirection.Output;

However this error comes up:

String[1]: the Size property has an invalid size of 0.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
RuMoR
  • 775
  • 1
  • 5
  • 7
  • For anyone with this same problem but for an `int` or other parameter type, you should specify the DbType of the SqlParameter object. I wasn't doing that and received this same error message. – Rory Oct 14 '22 at 21:49
  • OMG! That is a HORRIBLE error message, one of the worst. The least they could do is give the parameter name or stored procedure name in the error message like they do on other errors. I'm so glad you posted, thanks for saving me HUGE amounts of time finding an answer. – Jay Imerman Jan 18 '23 at 01:10

4 Answers4

134

You need to define a length when specifying the varchar parameter:

SqlParameter job1 = cmd2.Parameters.Add("@job", SqlDbType.VarChar, 50);

You should use the same length as defined in your SQL Server stored procedure.

And btw: if your stored procedure also has no length defined (something like @job VARCHAR OUTPUT) - then you've defined a varchar string of 1 character length ......

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • I have a question because I have the same exception...if the column is varchar, what is the danger of having varchar in your SP and code using DbType.AnsiString – Chillin' Mar 05 '19 at 15:36
  • 2
    It is known as the "Size" attribute in case you need to specify it like I did – thalacker Aug 21 '19 at 22:04
11

Yes, have to define the length for varchar / nvarchar data type like below.

cmd.Parameters.Add("@Description", SqlDbType.VarChar, 150).Direction =
    ParameterDirection.Output;
Bojan B
  • 2,091
  • 4
  • 18
  • 26
5

If you are using Dapper, you have passed in a null value for the parameter, where the expected input was a string.

To find the offending value and it's parameter, inspect at the Dapper DynamicParameters object during a debug session and open the parameters being index referred to.

enter image description here

tno2007
  • 1,993
  • 25
  • 16
1

Assign an empty string to the output parameter before calling the stored procedure and that should get rid of the error:

job1.Value = string.Empty;

ChrisC
  • 237
  • 2
  • 2