When I try this ad-hoc query in SQL Server (assume UserId is a NVARCHAR field):
SELECT * FROM MyUser WHERE UserId = 123456
I get this error:
Msg 245, Level 16, State 1, Line 1 Syntax error converting the nvarchar value 'foo' to a column of data type int.
Obviously there is a value 'foo' somewhere down my UserId column.
Why is SQL Server trying to convert my entire column to INTEGER instead of doing what seems obvious to me: converting my search value to NVARCHAR?
The comparison is done using the rules of Data Type Precedence:
The
NVARCHARtype (precedence 25) is converted toint(precedence 16). Note that precedence 1 means ‘highest’.