如何告诉SQL Server将错误的数字字段解释为零

时间:2018-03-30 15:50:56

标签: sql-server tsql

我在下面的查询失败,因为某些行不能解释为数字。有人在数量列中输入字母字符。我希望将它们视为零(就像我对使用强制转换的NULL所做的那样)。

我将如何做到这一点?

Select 
    DocId, AR_Numbers, PONO, Product, 
    Sum(Cast(ISNULL(Quantity, 0) as decimal)) as Qty 
from 
    (Select 
         ARs.DocID, Ars.Field61 as AR_Numbers, PONOs.Field21 as PONO, 
         CoreData.Field9 as Product, CoreData.Field10 as Quantity 
     from 
         ssMVFields ARs 
     left join 
         ssFields PONOs on ARs.DocId = PONOs.DocId 
     left join 
         ssField14 as CoreData on Ars.DocID = CoreData.DocID) as AAA
Group by 
    DocId, AR_Numbers, PONO, Product

5 个答案:

答案 0 :(得分:2)

函数try_cast恰好适用于此:

isnull(try_cast(quantity as int), 0)

答案 1 :(得分:1)

您可以使用TRY_CAST尝试将字段转换为数字,如果失败则返回null,然后您可以用0替换null:

{{3}}

答案 2 :(得分:0)

不确定您的查询在哪里需要这样做,但您可以使用案例陈述:

SELECT CASE WHEN ISNUMERIC(YourFieldHere) = 0 THEN 0 ELSE YourFieldHere END

检查字段是否为数字,如果不是则返回0.这应适用于大多数/所有数字,包括小数。

答案 3 :(得分:0)

此查询不需要子查询。但从根本上说,我建议try_convert()

select DocId, Ars.Field61 as AR_Numbers, PONOs.Field21 as PONO,
       CoreData.Field9 as Product, 
       sum(try_convert(decimal, CoreData.Field10)) as Qty
from ssMVFields ARs left join
     ssFields PONOs
     on ARs.DocId = PONOs.DocId left join
     ssField14 CoreData
     on Ars.DocID = CoreData.DocID
group by DocId, Ars.Field61, PONOs.Field21, CoreData.Field9

答案 4 :(得分:0)

在投射前使用ISNUMERIC('Fieldvalue')检查