使用Linq to SQL的SQL中的小数精度问题

时间:2010-02-24 15:39:31

标签: c# sql-server-2005 linq-to-sql

我有一个简单的查询:

var results = from k in db.tree_nodes
              join s in db.stocks
              on k.tree_nodes_id equals s.tree_nodes_id
              into tmpTable
              from rowtmp in tmpTable.DefaultIfEmpty()
              select new
              {
                  stock = (rowtmp.amount == null) ?
                           ((k.code == null) ? (decimal?)null : (decimal?)0)
                           :
                           rowtmp.amount - rowtmp.amount_in_use,
              };

这是生成的SQL代码:

SELECT 
    (CASE 
        WHEN ([t1].[amount]) IS NULL THEN 
            (CASE 
                WHEN [t0].[code] IS NULL THEN CONVERT(Decimal(33,4),NULL)
                ELSE CONVERT(Decimal(33,4),0)
             END)
        ELSE CONVERT(Decimal(33,4),[t1].[amount] - [t1].[amount_in_use])
     END) AS [stock]
FROM [dbo].[tree_nodes] AS [t0]
LEFT OUTER JOIN [dbo].[stocks] AS [t1] ON [t0].[tree_nodes_id] = [t1].[tree_nodes_id]

问题是,生成器在转换结果时创建了Decimal(33,4)。所以我在结果中得到“ 123.4560 ”而不是“ 123.456 ”此查询中的所有字段都是decimal(14,3)。我不介意 33 部分,但我需要将,4 更改为,3 。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

您可以将小数值四舍五入到小数点后三位吗?

var results = from k in db.tree_nodes
              join s in db.stocks
              on k.tree_nodes_id equals s.tree_nodes_id
              into tmpTable
              from rowtmp in tmpTable.DefaultIfEmpty()
              select new
              {
                  stock = (rowtmp.amount == null) ?
                           ((k.code == null) ? (decimal?)null : (decimal?)0)
                           :
                           decimal.Round(rowtmp.amount,3) - decimal.Round(rowtmp.amount_in_use == null ? 0 : rowtmp.amount_in_use,3),
              };

不知道任何阻止linq-to-sql进行类型转换的方法。