I'm working on a c# application with a sql server 2005 database.
what is the best way to convert to decimal a value brought to a datareader from a database, not knowing if the value that is coming from the base is a decimal or is a bigint ?
if (dataReader.IsDBNull(0) == false) {
PLAYER.PLAYER_ID = dataReader.GetDecimal(0);
}
In my PLAYER object, PLAYER_ID is decimal type.
I use two different databases, therefore, the value that comes from the base can be bigint or decimal. If this is decimal thete's no problem, but if it's a bigint, i get an error.
You should be able to use the GetFieldType method to determine the data type of the object.
You can use GetFieldType to determine the type
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getfieldtype.aspx
Type type = dataReader.GetFieldType(0);
You can then use an appropriate reader method to read out the data.
You probably want to avoid calling GetFieldType for every row. Call it before you start reading rows and set a flag indicating which type this particular query returned.
Use Decimal.TryParse:
decimal tempID;
Decimal.TryParse(dataReader[0], out tempID);
PLAYER.PLAYER_ID = tempID;
It should convert the value to the decimal unless it's null. If it's null decimal will remain 0.
Related
I have written a stored procedure which returns one of the value as REAL datatype since it is referring to some old database table.
I want to convert/map this value to a decimal? type in C#. However, I get an error:
Specified cast not valid
when running this code:
item.SludgeCapacity =v.Field<decimal?>("SludgeCapacity");
Does anyone have an optimised solution?
try
item.SludgeCapacity = Convert.ToDecimal(v.Field("SludgeCapacity"));
I need to get the exact type of a column in a DataTable in C#.
In a simliar article on SO i found part of a solution:
DataTable st = reader.GetSchemaTable();
foreach (DataRow row in st.Rows)
{
Console.Write(string.Format("ColumnName:{0} DataType:{1} Ordinal:{2} Precision:{3} Size:{4} Scale:{5}",
row["ColumnName"], row["DataTypeName"], row["ColumnOrdinal"],
row["NumericPrecision"], row["ColumnSize"], row["NumericScale"]));
}
This works for string and date so far.
But for decimal i always recieve nullfor precision and scale.
I need those values to create a new table in another database.
The DataType returned is Decimal.
In the MSDN documentation it says that NumericPrecision returns null if it is no numeric data type, but decimal is kind of numeric?
So how do i get the exact precision of decimal values from the DataSet? Or rather what am I doing wrong?
edit:
I am trying to create some new SQL database based on old .dbf files from a FoxPro application.
So i want to read the columns, and create them in SQL, therefore I need the exact type of the column.
I tried with the .dbf and a new sql database.
I created a table in both to know the exact type for sure, for both databases i get those null returns. There is only a problem with the decimal/numeric values, for string and DateTime i get the Size.
For the .dbf I use a OleDbConnection.
For the SQL I use a SqlConnection, I get null if I try it for each.
From my experience with MySQL, the decimal datatype is numeric, but it can hold any precision or scale. If the database you are trying to create doesn't have the decimal datatype, you may need to convert it to a different type of number and possibly guess what precision and scale you need.
I have an asp.net application written in C#. I have an insert button that takes user-entered information on the page, adds the values to a list, and sends the list to a method that inserts the data to a MSSQL database table.
Everything is working as expected except for fields with data type set to 'float' on the backend.
If I enter a value such as '70.3' in the textbox for field 'Temperature', the value inserted actually becomes '70.3000030517578'. I also have a button that calls an update method. If I change the '70.3000030517578' back to '70.3' and send it to the update method, then 70.3 is correctly inserted in the database.
Here is my SqlCommand Parameter code:
cmd.Parameters.AddWithValue("#temp", listIn[0].Temperature == null ? (object)DBNull.Value : listIn[0].Temperature);
After the above line runs, I check the parameter in debugging mode and confirmed that the Value is 70.3. See screenshot:
I compared this to the update since that method works properly and the properties become:
The two differences are in the DbType and SqlDbType.
So I tried the below line which did not change anything (still adds extra decimal places):
cmd.Parameters.Add("#temp", SqlDbType.Float).Value = listIn[0].Temperature == null ? (object)DBNull.Value : listIn[0].Temperature;
If I change the data type on the backend to decimal(18,3) then the insert method correctly inserts '70.300'. Is my only option to use decimal data type instead of float? We would prefer to use float, if possible. Any ideas are welcomed. I have not been doing this long so I apologize if my question is not detailed enough.
Read about Using decimal, float, and real Data
Approximate numeric data types do not store the exact values specified
for many numbers; they store an extremely close approximation of the
value. For many applications, the tiny difference between the
specified value and the stored approximation is not noticeable. At
times, though, the difference becomes noticeable. Because of the
approximate nature of the float and real data types, do not use these
data types when exact numeric behavior is required, such as in
financial applications, in operations involving rounding, or in
equality checks. Instead, use the integer, decimal, money, or
smallmoney data types.
You're probably running into something related to floating point precision/error. 70.3 is not a value that can be precisely represented in the float/real type. The closest value that can be stored (following IEEE-754 standards) is 70.30000305175781
http://www.h-schmidt.net/FloatConverter/IEEE754.html
If you need accuracy in base 10, decimal is probably the way to go. Otherwise, you'll have to do the rounding yourself.
I am writing application with ADO.NET and want to select a value which is of type numeric(9, 2). But I don't know how to use this value, I mean I'm not able to cast this value.
So to which datatype it should be casted to.
Decimal decimalLastModifiedWaitingForApprovalcurrency = 0;
decimalLastModifiedWaitingForApprovalcurrency = (Decimal)(cmd.ExecuteScalar());
I have tried this also
Convert.ToDecimal(cmd.ExecuteScalar());
I have considerred that this could be casted to Decimal, But its giving error.
So whats numeric equivalent of SQL server numeric datatype in C#?
Since you are using ExecuteScalar(), it is returning the value as object. If you aren't quite sure what CLI type it has chosen, just look at:
object value = cmd.ExecuteScalar();
Debug.WriteLine(value.GetType().Name);
Decimal only. You are using correct data type.
Check the complete list SQL Server Data Type Mappings
try Convert.ToDouble(cmd.ExecuteScalar()); and let me know if this does not work.
When I am Entering a double number from C# to the DB I use a real type in the DB. When I check the value it is exactly what I enter.
Now when I go to retreive the value from the DB and store it into a C# double, it adds random decimal values at then end. The number in the database is the correct value that I want, but the value in C# as a double is just random (sometimes higher sometimes lower then the actual value.)
ie
- Enter into the db 123.43 as a double to an sql real.
- View the value in the DB, it's exactly 123.43
- Get the value from the DB and store into a C# double, value in the double is now 123.4300000305176
I have tried changing the type to float, decimal, etc. in the DB but these types actually alter the value when I put it into the DB to the same format as the above.
Any help on whats going on or how to fix it?
You should probably be using Decimal type. See What represents a double in sql server? for further explanation.
Try using a Single if your DB type is real. Check here for data mappings http://msdn.microsoft.com/en-us/library/ms131092.aspx