2

I want to read a number of type decimal(8,2) from a SQL Server database, and store them in an object, MyRow.

public class MyRow
{
    public decimal data1 { get; set; }
}

...

List<MyRow> values = new List<MyRow>();
SqlDataReader reader = command.ExecuteReader();

while (reader.read())
{
    values.Add( new MyRow() { 
        data1 = decimal.Parse(((double)reader["data1"]).ToString("R")) 
    }
}

This solution seems far from ideal, and it seems like I'm doing too much conversion for something that seems like it would be fairly simple. Since the values for data are already decimal(8,2) in the database, is there any way to read the data into a decimal type without the conversion from an object to a decimal?

4 Answers 4

2

You could use the GetDecimal method of SqlDataReader. A SqlDataReader object implmements the IDataRecord interface. Hence, it implements many methods. Among these methods, there is the GetDecimal.

For further information on this, please have a look here.

That being said, your code can be written as below:

List<MyRow> values = new List<MyRow>();
SqlDataReader reader = command.ExecuteReader();
while (reader.read())
{
    values.Add(new MyRow() 
    { 
        data1 = reader.GetDecimal(reader.GetOrdinal("data1")) 
    });
}
0

Have you checked out the SqlDataReader.GetDecimal method?

0

Use SqlDataReader's GetDecimal method.

var values = new List<MyRow>();
while (reader.Read())
{
   var r = new MyRow { data1 = reader.GetDecimal(reader.GetOrdinal("data1"))};
   values.Add(r);
}
0

Use Precision and Scale

Here the code snippet

// Assume, com is SqlCommand and ExchangeRate is Parameter

SqlParameter parameter = new SqlParameter("@ExChangedRate", SqlDbType.Decimal);
parameter.Direction = ParameterDirection.Output;
parameter.Precision = 16;
parameter.Scale = 2;
com.Parameters.Add(parameter);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.