I have a DataTable that has a string type column filled with valid numeric values and I need to get a sum of those values. Please understand that if I was in control of the data I’m working with in this instance, I would not have used a string column to store “Cost” but that is the unfortunate reality. I’ve been using the DataTable.Compute method with the “SUM(Convert([Column],’DataType’))” expression and no filter. The problem is that I get the following exception:
System.Data.SyntaxErrorException – Syntax error in aggregate argument: Expecting a single column argument with possible ‘Child’ qualifier.
I’ve put together a small block of code that successfully reproduces the issue that I’m having.
DataTable dt = new DataTable();
dt.Columns.Add("Cost", typeof(string));
dt.Rows.Add(new object[] { "1" });
dt.Rows.Add(new object[] { "3.25" });
dt.Rows.Add(new object[] { "0.75" });
object TotalCost = dt.Compute("Sum(Convert(Cost,'System.Decimal'))", "");
One last note, I am restricted to .NET 2.0 so using LINQ to get through this isn’t an option at the present time.
Wouldn’t it be simpler to define the column data type to store number, than string?
EDIT: How about adding a new temporary column to do the conversion, summing it up & removing it?