简体   繁体   中英

SQL Server Database store number data as exponential

I have a simple console application that reads from an excel file (source.xlsx) using OpenXML and do SQL Insert using ADO.NET to save the data to a SQL Server Database.

I found problem when I read a decimal number like 0.00015, in which after saving to the SQL Server, it will be saved as "1.5 E-2" instead of 0.00015.

This problem occurs when I try to run it in the production environment, but not occur when I try to run it in the staging environment (in the staging environment, it is saved as 0.00015).

As far as the differences between the environment, I haven't found anything useful, so far all the settings looks the same (I most likely missing something important).

What is likely the root cause of the data stored that way and how to prevent it?

One likely cause would be if you are creating your SQL Insert statement using something like this:

float value = 0.00015f;
string sql = "INSERT INTO [mytable] ([fieldname]) VALUES (" + value.ToString() + ")";

or

string sql = string.Format("INSERT INTO [mytable] ([fieldname]) VALUES ({0})", value);

Both of these rely on .net's string formatting to produce valid SQL, which is not safe. The default string formatting will produce "The more compact of either fixed-point or scientific notation." So you will sometimes get scientific notation (1.5E-5), and sometimes fixed point formatting (0.00015). You may have different cultures on the server and development environments which could affect which format is more compact.

The correct way to do this is to use parameters in your SQL, to avoid formatting problems and SQL injections:

using (var cmd = dbConnection.CreateCommand()) {
    var prm = cmd.CreateParameter();
    prm.ParameterName = "value";
    prm.DbType = DbType.Single;
    prm.Direction = ParameterDirection.Input;
    prm.Value = 0.00015f;
    cmd.Parameters.Add(prm);

    cmd.CommandText = "INSERT INTO [mytable] ([fieldname]) VALUES (@value)";
    cmd.ExecuteNonQuery();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM