How To Convert The DataTable Column type?

房东的猫 提交于 2020-01-10 06:04:14

问题


I am trying to implement:

dtGroupedBy.Compute("sum(POWER)",dvv.RowFilter); 

It results of an error:

Invalid usage of aggregate function Sum() and Type: String.

How would we convert it to its column type ??


回答1:


Compute method supports expressions and they support the CONVERT function that you could use inside of the expression.

For example, you could calculate sum of the column like

MyDataTable.Compute("Sum(Convert(your column name, 'Data Type'))") 



回答2:


It will depend on how you've created the DataTable. If it's just straight from SQL, you should look into changing the SQL itself so that the POWER column is converted as you fetch it.

However, if the value should always be numeric in the first place, I would strongly suggest that you revisit your database schema - it would be cleaner to change the column type if you possible can.




回答3:


You can't use the Sum() aggregate function on a string field.

There are 2 things you can do

  • Redefine your existing column item in your db (or schema) to be a numeric field.(recommended)
  • do a System.Int32 conversion on the data you're passing to the aggregate function. so you could do the following

dtGroupedBy.Compute("sum(CONVERT(" + POWER + ",'System.Int32'))",dvv.RowFilter);



来源:https://stackoverflow.com/questions/6567787/how-to-convert-the-datatable-column-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!