Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unexpected "Conversion Failed"

SQL Server 2017
SSMS 18.12.1

I expect a result query with a scalar 5.

But I got error message 245

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Conversion failed when converting the varchar value ‘FPO’ to data type tinyint

What am I doing wrong?

CREATE TABLE TabA(aNumVal TINYINT NOT NULL)

INSERT INTO TabA (aNumVal) VALUES(5)
INSERT INTO TabA (aNumVal) VALUES(2)
    
CREATE TABLE TabB(aCharVal VARCHAR(3) NOT NULL)

INSERT INTO TabB (aCharVal) VALUES('FPO')
INSERT INTO TabB (aCharVal) VALUES('2')

SELECT aNumVal
FROM TabA
WHERE aNumVal NOT IN (SELECT aCharVal FROM TabB 
                      WHERE ISNUMERIC(aCharVal) = 1)

>Solution :

SQL server will perform type conversion when comparing data. VARCHAR is converted to INT. There is absolutely no guarantee at which stage it is done. It could be done before evaluating WHERE clause if the server decides so.

The possible work around is to use TRY_CAST:

WHERE aNumVal NOT IN (
    SELECT TRY_CAST(aCharVal AS INT)
    FROM TabB
    WHERE TRY_CAST(aCharVal AS INT) IS NOT NULL
)

The IS NOT NULL is required for NOT IN checks.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading