Friday, February 10, 2012

CAST error with nvarchar to int (Error converting data type nvarchar to int)

I am receiving an error with a transact query when performing a CAST from an nvarchar to int. For example:

SELECT myField1, CAST(myField2 as int) FROM tbl_myTable

MSDN article describe that this casting error "Error converting data type nvarchar to float" is caused by an invalid non-numeric entry.

Is there a way to perform an in-line test to perform a check to determine a course of action? For example:

SELECT myField1, IIF(isNumber(myField2) = 1, CAST(myField2 as int),0) FROM tbl_myTable

Are above expression, or something similar to it, even possible in transact-SQL?

Thank you,
Each column in a select stmt can only be one data type. Why do you need to check each row to see if it is an int or not?|||Due to requirements, it is necessary to "transform" data from nvarchar into int (in a massive sweep).

I think I have been able to figure this out using CAST

Instead of : SELECT myField1, IIF(isNumber(myField2) = 1, CAST(myField2 as int),0) FROM tbl_myTable

Following I think will work:
SELECT myFIeld1, CASECAST isNumeric(myField2) WHEN 1 THEN CAST(myField2 as int) ELSE NULL END as myField2 FROM tbl_myTable

What do you think?
|||

CAST and CONVERT are the same, CAST is just the standard.

Code Snippet

SELECT field1, CASE WHEN IsNumeric(myField2) = 1 THEN CAST(myField2 as int) ELSE NULL END as myField2 FROM table

anything other than NULL and int wont work though.|||Sorry for a bit of a typo, meant to write the following:

Instead of : SELECT myField1, IIF(isNumber(myField2) = 1, CAST(myField2 as int),0) FROM tbl_myTable

Following I think will work:
SELECT myFIeld1, CASE isNumeric(myField2) WHEN 1 THEN CAST(myField2 as int) ELSE NULL END as myField2 FROM tbl_myTable

What do you think?
|||yes, that works fine|||Thank you to everyone who replied!

No comments:

Post a Comment