This is a general mistake that many developers do and sometimes goes unnoticed while reviews and testing, but then suddenly one day start appearing as bugs.

Many developers understand and (misinterpret) varchar as variable-length data type and hence doesn’t specify the length in the variable definitions which is incorrect. Here are some examples of ‘weird’ behavior of incorrectly defined varchar. Here is some demo

SET @var='This string will get truncated'

SELECT CAST ('This is very very long string which will get truncated' AS VARCHAR)

Here is the result

Varchar sizing

The data types CHAR, NVARCHAR, NCHAR, DECIMAL, NUMERIC also work in the same faction. ┬áSo next time when you define a variable, don’t forget to specify the lengths properly.

Question from MSDN forums

Leave a Reply

Your email address will not be published. Required fields are marked *