treeblah
treeblah

Reputation: 1265

Read decimal from SQL Server database

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?

Upvotes: 2

Views: 6924

Answers (4)

vel
vel

Reputation: 1

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);

Upvotes: 0

Christos
Christos

Reputation: 53958

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")) 
    });
}

Upvotes: 2

Shyju
Shyju

Reputation: 218782

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);
}

Upvotes: 0

Dan Forbes
Dan Forbes

Reputation: 2824

Have you checked out the SqlDataReader.GetDecimal method?

Upvotes: 0

Related Questions