SQLite圆中点

时间:2015-07-29 11:01:58

标签: sqlite sqlite-net

我正在尝试像这样使用SQLite函数ROUND:

select ROUND(1.655, 2)

结果是1.65,但是我需要将其舍入到1.66,就像在c#

上一样
Math.Round(1.655, 2, MidpointRounding.AwayFromZero)

有办法做到这一点吗?

1 个答案:

答案 0 :(得分:0)

所以我一直在努力使用使用Binding functions的Colonel Thirty Two提示,但sqlite-net不提供此类功能。 我转向System.Data.SQLite.dll,以帮助其他人:

首先在c#

中创建自定义函数
[SQLiteFunction(Name = "RoundAccounting", Arguments = 2, FuncType = FunctionType.Scalar)]
public class RoundAccounting : SQLiteFunction
{
    public override object Invoke(object[] args)
    {
        decimal value = 0;
        int decimalPlaces = 0;

        if(decimal.TryParse(args[0].ToString(), out value) && int.TryParse(args[1].ToString(), out decimalPlaces))
            return Math.Round(value, decimalPlaces, MidpointRounding.AwayFromZero);

        return 0;
    }
}

然后在数据层上我们将函数绑定到创建的连接:

using (SQLiteConnection connection = new SQLiteConnection(string.Format("Data Source={0}", dbPath)))
        {
            var function = new RoundAccounting();
            var attributes = function.GetType().GetCustomAttributes(typeof(SQLiteFunctionAttribute), true).Cast<SQLiteFunctionAttribute>().ToArray();
            await connection.OpenAsync();
            connection.BindFunction(attributes[0], function);

            SQLiteCommand command = new SQLiteCommand("SELECT RoundAccounting(somecolumn, 2);", connection); .....