Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to insert decimal to sql server table through c# code

I'm not able to insert decimal values into Sql Server table.

What i'm trying to do is self explanatory through these lines of code:

long fileSizeInBytes = ComponentUploadControl.FileContent.Length;
Decimal fileSizeInMB = Convert.ToDecimal(fileSizeInBytes) / (1024.0m * 1024.0m);
Decimal fileSizeInMBRounded = Math.Round(fileSizeInMB, 2);
cmd.Parameters.Add("@fileSize", SqlDbType.Decimal).Value = fileSizeInMBRounded;

The value that is getting inserted into database is stripped of the decimal places. To be more specific if the fileSizeInMBRounded is 11.73, the value that is getting inserted into database is 11,00

Please help me

Thanks in anticipation

like image 660
Sree Avatar asked May 02 '11 14:05

Sree


People also ask

How do you insert decimals in SQL?

In standard SQL, the syntax DECIMAL( M ) is equivalent to DECIMAL( M ,0) . Similarly, the syntax DECIMAL is equivalent to DECIMAL( M ,0) , where the implementation is permitted to decide the value of M . MySQL supports both of these variant forms of DECIMAL syntax. The default value of M is 10.

How do I fix decimal places in SQL?

The ROUND() function rounds a number to a specified number of decimal places.

Can an INT hold a decimal in SQL?

As we know from before, integers are whole numbers, or numbers with no fractions (i.e. no decimal places). This is going to be in the test later, so pay attention. In other words, the numbers 0 through 9 are integers, but a floating point or decimal / numeric value is not an integer.

Is decimal a data type in SQL Server?

The DECIMAL data type is an exact number with a fixed precision and scale. Precision is an integer representing the total number of digits allowed in a column. Scale is also an integer value that represents the number of decimal places.


3 Answers

My suspicion is that your decimal field is set up wrong in SQL. What you want is a decimal(18,2) field which allows for 2 decimal places. My suspicion is that you declared the field as decimal(18,0) (the default), which does not allow for any decimal places.

If you can use SQL Server Profiler to verify the contents of the INSERT going to your DB, it would be easier for you to determine whether a problem like this is due to your code or something on the SQL server.

like image 197
pseudocoder Avatar answered Sep 21 '22 04:09

pseudocoder


Try to set the SqlParameter.Scale to 2.

SqlParameter parameter = new SqlParameter("@fileSize", SqlDbType.Decimal);
parameter.Scale = 2;
parameter.Value = fileSizeInMBRounded;
cmd.Parameters.Add(parameter);

Also look into Precision property as suggested by Bruno (default is 0).

like image 29
Bala R Avatar answered Sep 20 '22 04:09

Bala R


You should set Scale and Precision.

I think that is the problem.

like image 20
Bruno Costa Avatar answered Sep 21 '22 04:09

Bruno Costa