Failed to convert parameter value from a String to a Decimal

John x picture John x · Aug 20, 2012 · Viewed 12.4k times · Source

Im importing a csv to my sql server table using the following code

SqlCommand nonqueryCommand = myConnection.CreateCommand();
nonqueryCommand.CommandText = 
                 "INSERT INTO MYTABLE VALUES(@num1, @num2,@num3,@num4)";

nonqueryCommand.Parameters.Add("@num1",SqlDbType.Decimal);
nonqueryCommand.Parameters.Add("@num2", SqlDbType.Decimal);
nonqueryCommand.Parameters.Add("@num3", SqlDbType.Decimal);
nonqueryCommand.Parameters.Add("@num4", SqlDbType.Decimal);

nonqueryCommand.Parameters["@num1"].Value = crntRecord[0];
nonqueryCommand.Parameters["@num2"].Value = crntRecord[1];
nonqueryCommand.Parameters["@num3"].Value =crntRecord[3];
nonqueryCommand.Parameters["@num4"].Value = crntRecord[4];

nonqueryCommand.ExecuteNonQuery();

where the parameter 3 and 4 are of type decimal(9,6) in the DDL when i execute the code at ExecuteNonQuery i get the following exception

Failed to convert parameter value from a String to a Decimal.

please help me find out the problem tnx.

EDIT

the value in the crntRecord[3] looks like

enter image description here

Answer

Daniel Mann picture Daniel Mann · Aug 20, 2012

Assuming that crntRecord is an array of strings, you need to parse the strings to a decimal first.

Ex:

nonqueryCommand.Parameters["@num3"].Value = decimal.Parse(crntRecord[3].ToString());

Note that this will throw an exception if crntRecord[3] is not parseable to a decimal; if that's a situation that could occur, look into decimal.TryParse() instead.