Friday, May 12, 2006

Syntax Error Converting The Varchar Value To A Column Of Data Type Int

There was a question today on the microsoft.public.sqlserver.programming forum where a person had a problem with an in predicate
The error that was raised was 'Syntax error converting the varchar value '33333A' to a column of data type int'
The error is a little bit misleading
Let's say you have the following query

SELECT * FROM SomeTable WHERE SomeColumn in (12345,22222)

And you get that error, you might think I am not converting anything why am I getting this error?
If the query was the one below then it would make sense

SELECT CONVERT(INT,SomeColumn) FROM SomeTable...

Now let's see what causes this error


--Create the test table and insert 3 rows of data
CREATE TABLE SomeTable (id INT,SomeColumn VARCHAR(49))
INSERT INTO SomeTable VALUES(1,'12345')
INSERT INTO SomeTable VALUES(1,'22222')
INSERT INTO SomeTable VALUES(1,'33333')

--let's select from that table
--no problem
SELECT * FROM SomeTable WHERE SomeColumn in (12345,22222)


--Let's insert something with a non numeric value
INSERT INTO SomeTable VALUES(1,'33333A')


--Let's try again
SELECT * FROM SomeTable WHERE SomeColumn in (12345,22222)
--Oops error
--Server: Msg 245, Level 16, State 1, Line 1
--Syntax error converting the varchar value '33333A' to a column of data type int.



--The trick is to put quotes around the values
--And now it works
SELECT * FROM SomeTable WHERE SomeColumn in ('12345','22222')

--Clean up
DROP TABLE SomeTable

No comments: