SQLCommand.Parameters.Add - How to give decimal value size?

Tony D. picture Tony D. · Jul 13, 2015 · Viewed 16.4k times · Source

How would you specify this:

Decimal(18,2)

In this:

SqlComm.Parameters.Add("@myValue", SqlDbType.Decimal, 0, "myValue");

Currently I have defined precision = 2 from the design side properties. I'm just curious as to how to accomplish this from the code. Thanks

Answer

D Stanley picture D Stanley · Jul 13, 2015

There's not an overload of Add that lets you set the decimal precision inline, so you either need to create a SQlParameter object and add it to the collection:

SqlParameter param = new SqlParameter("@myValue", SqlDbType.Decimal);
param.SourceColumn = "myValue";
param.Precision = 18;
param.Scale = 2;
SqlComm.Parameters.Add(param);

or "find" the parameter after adding it:

SqlComm.Parameters.Add("@myValue", SqlDbType.Decimal, 0, "myValue");
SqlParameter param = SqlComm.Parameters["@myValue"];
param.Precision = 18;
param.Scale = 2;

or using the parameter constructor:

SqlComm.Parameters.Add(new SqlParameter(
    parameterName = "@myValue", 
    dbType = SqlDbType.Decimal,
    precision = 18,
    scale = 2,
    sourceColumn = "myValue"));