开发者

Sql query to convert nvarchar to int

I have to query for total amount of a column using an aggregate function. The col开发者_Go百科umn data type is NVARCHAR(MAX). How can I convert it to Integer?

I have tried this:

  SELECT SUM(CAST(amount AS INT)),
         branch 
    FROM tblproducts  
   WHERE id = 4
GROUP BY branch

...but I'm getting:

Conversion failed when converting the nvarchar value '3600.00' to data type int.


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


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 ) 


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜