Yes, this is a common theme, which has its root cause in that SQL has implicit conversion between strings and numbers in differences to many other statically typed languages. If that had been forbidden, you would have had to tackle the situation from the start.
The query above works fine as long as the query plan first filters for the IdKeyName, and wait with converting IdNumber until later. However, the optimizer may decide to perform the conversion before the filtering, and in that case the query fails. You could argue that this behaviour is incorrect, but it is not unique to SQL Server. I recall having seen a blog post about a similar behaviour in Oracle.
The correct solution is to use an explicit convert:
select @idPerson = try_convert(bigint, IdNumber)
It is important to use try_convert
, which returns NULL when conversion fails.