Monday, March 2, 2015

Error converting data type varchar to numeric

I have faced this error "error while converting data type varchar to numeric" several times when converting string data to numeric. Every time I found a unique solution .

This usually happens in a scenario when we do not have much control over the data which is being pulled from different source, which again could be a private internal data or data from external public sites.

Recently in one of my projects while pulling data from external url I faced this issue to convert string data to numeric.

Following are few steps I follow to troubleshoot this error :-)

  • Make sure the column used for conversion doesn't have any visible special characters. If any then try to replace them. 
  • Make sure to use the replace for non visible characters like TAB, Line Feed, Carriage Return. In T-SQL these are can be identified using CHAR function
    • TAB => CHAR(9)
    • Line Feed => CHAR(10)
    • Carriage Return => CHAR(13) (Resource: MSDN )
  • So use the replace function to replace the above non visible characters with '' (space).
  • There are few scenario's where after doing all these I still get the error. To solve this I recently used the ASCII() function. Use this function to know if there are any unwanted non visible data in the column. Probably update the column to '0.0' where ASCII(ColumnName) IS NULL.
Let me know if you are aware of any other methods to handle this error.

No comments:

Post a Comment