Using SqlDBType.Decimal in Prepared Statement C#

后端 未结 4 1955
难免孤独
难免孤独 2021-01-11 10:56

am using a Prepared Statement in C#.

 SqlCommand inscommand = new SqlCommand(supInsert, connection);
 inscommand.Parameters.Add(\"@ordQty\", SqlDbType.Decim         


        
相关标签:
4条回答
  • 2021-01-11 11:06

    As the exception pointed out, you have to explicitly set the SqlParameter.Precision and SqlParameter.Scale properties in order to use the decimal type as a parameter.

    Let's say your SQL field is of type decimal(18,8). The way to do this inline is to use brace-initialization for your SqlParameter while adding it to the SqlParameterCollection, as follows:

    cmd.Parameters.Add(new SqlParameter("@ordGty", SqlDbType.Decimal) {
        Precision = 18, Scale = 8 });
    

    You can also do

    cmd.Parameters.Add(new SqlParameter("@ordGty", SqlDbType.Decimal) {
        Precision = 18, Scale = 8}).Value = 0.4m; // or whatever
    

    to add the value, if you need one. You could even do

    cmd.Parameters.Add(new SqlParameter("@ordGty", SqlDbType.Decimal) {
        Precision = 18, Scale = 8, Value = 0.4m /* or whatever */});
    

    if you prefer. Brace initialization is really powerful.

    Side note: I realize that this is an old question, but I think this form is much more readable than creating the object while adding it to the list and then setting the scale and precision. For Posterity! (since this is a high-listing google search result)

    0 讨论(0)
  • 2021-01-11 11:15

    try this:

    SqlParameter parameter = new SqlParameter("@ordQty", SqlDbType.Decimal);
    parameter.Precision = 18;
    parameter.Scale = 0;
    parameter.Value = YOURVALUEHERE;
    inscommand.Parameters.Add(parameter);
    
    0 讨论(0)
  • 2021-01-11 11:17

    You will have to explicitly define precision and scale for this parameter.

    SqlParameter ordQty = cmd.Parameters.Add("@ordQty", SqlDbType.Decimal);
    ordQty.Precision = x; //Replace x with what you expect in Sql Sp
    ordQty.Scale = y; //Replace y with what you expect in Sql Sp
    ordQty.Value = 18; //Set value here
    inscommand.Parameters.Add(ordQty);
    
    0 讨论(0)
  • 2021-01-11 11:28

    The following would set a Decimal with Precision 18 and Scale 8 (Decimal (18,8))

    SqlCommand insertCommand= new SqlCommand(supInsert, connection);
    insertCommand.Parameters.Add("@ordQty", SqlDbType.Decimal,18);
    
    insertCommand.Parameters["@ordQty"].Precision = 18;
    insertCommand.Parameters["@ordQty"].Scale = 8;
    
    insertCommand.Prepare();
    u = insertCommand.ExecuteNonQuery();
    
    0 讨论(0)
提交回复
热议问题