Blog Post

Azure Database Support Blog
1 MIN READ

Lesson Learned #302: System.InvalidCastException: Specified cast is not valid

Jose_Manuel_Jurado's avatar
Jan 24, 2023

Today, we have a service request that our customer faced the following error message: System.InvalidCastException: Specified cast is not valid reading a Resultset or doing any operation with the database.

 

Following, I would like to share my lessons learned with this issue. 

 

  • First, I would like to check if this error is raising by SQL Database. For this reason, I wrote down this small TSQL-code:

 

 

create procedure MyCodeTest(@state as int) 
as select @state

 

 

  • Calling EXEC MyCodeTest 'X' we got the following error: Msg 8114, Level 16, State 1, Procedure MyCodeTest, Line 0 [Batch Start Line 1] Error converting data type varchar to int. 
  • Even, running SELECT CAST('X' AS int) or SELECT CONVERT(int,'X'), our customer faced the problem: Msg 245, Level 16, State 1, Line 9 Conversion failed when converting the varchar value 'X' to data type int.

 

So, all points to, depending on, the value that the ResultSet is reading or the code conversion that is using is not the expecting values. In terms of coding, for example, in SQL Server TSQL we have TRY_PARSE (Transact-SQL) - SQL Server | Microsoft Learn to check the value conversion test before executing the conversion. 

 

Enjoy!

Updated Jan 24, 2023
Version 3.0

1 Comment

  • jindrich_matous's avatar
    jindrich_matous
    Copper Contributor

    Hallo Jose Manuel Jurado,

    thank you for a post. I have a question.

    SELECT cast(ValueText as float)
    FROM Results
    INNER JOIN Analyt
    ON Results.ModelName = Analyt.ModelName
    AND Results.DeviceTestID = Analyt.DeviceTestID
    WHERE Results.NonNumericValue = 0

    In some cases it raises an error "Error converting data type nvarchar to numeric." What is expected according the documentation. It is very hard to reproduce, but we know that it happens.
    Does the move of condition to SELECT clause change an issue? Or it is translated similar way in the SQL engine? GitHub Copilot means it is the same, but my boss doesn't trust it.

    SELECT CASE WHEN NonNumericValue = 0 THEN CAST(ValueText AS FLOAT) ELSE NULL END
    FROM QC_Results
    INNER JOIN Analyt_OC
    ON QC_Results.ModelName = Analyt_OC.ModelName
    AND QC_Results.DeviceTestID = Analyt_OC.DeviceTestID