These queries return unexpected results for me.
SELECT 'Test' WHERE '00001000' = 1000
SELECT 'Test' WHERE '00001000' = '1000'
SELECT 'Test' WHERE 0001000 = 1000
I would expect it to be no results, no results, results, but instead the first query returns results. It seems that SQL will try and convert the string to an int to do the comparison, instead of the other way around. Is there a reason for this?
答案 0 :(得分:3)
Based on the Data Type Precedence in SQL Server, whenever it encounters two differing datatypes on either side of an operator, it will try to convert both values to the data type with the higher preference.
In the case of int
vs. varchar
, it is int
- so SQL Server will try to convert both side of the equal sign to an int
and then compare - and in the case of your first statement, those values are in fact the same, so you get a result.