Sql query to convert nvarchar to int

前端 未结 3 814
星月不相逢
星月不相逢 2020-12-31 03:15

I have to query for total amount of a column using an aggregate function. The column data type is NVARCHAR(MAX). How can I convert it to Integer?

I have tried this:

相关标签:
3条回答
  • 2020-12-31 03:51

    3600.00 is not integer so CAST via float first

    sum(CAST(CAST(amount AS float) AS INT))
    

    Edit:

    Why float?

    • no idea of precision or scale across all rows: float is the lesser evil perhaps
    • empty string will cast to zero for float, fails on decimal
    • float accepts stuff like 5E-02, fails on decimal
    0 讨论(0)
  • 2020-12-31 03:56

    SELECT sum(Try_Parse(amount as Int Using 'en-US')), branch FROM tblproducts
    WHERE id = 4 GROUP BY branch

    0 讨论(0)
  • 2020-12-31 04:12

    In addition to gbn's answer, you need to protect against non-numeric cases:

    sum(CASE WHEN ISNUMERIC(Amount)=1 THEN CAST(CAST(amount AS float) AS INT)END ) 
    
    0 讨论(0)
提交回复
热议问题