Monday, July 29, 2013

Convert nvarchar to int in SQL


If your table has nvarchar column and there is integer data in this column , then inserting that data into int column type is not a problem.
But if data is float, then the data need to be converted to float datatype before cast to int to insert into int column type.

Example:
SELECT SUM(CAST(amount AS INT)),  title   FROM books GROUP BY title
...will give you:
Conversion failed when converting the nvarchar value '4500.00' to data type int.

Correct way

4500.00 is not integer so CAST via float first
sum(CAST(CAST(amount AS float) AS INT))

Why float?
  • no idea of precision or scale across all rows
  • empty string will cast to zero for float, fails on decimal
  • float accepts stuff like 7E-02, fails on decimal 

HTH

No comments: