You are probably working against:
DECLARE @part1 VARCHAR(5000)=REPLICATE('a',5000); DECLARE @part2 VARCHAR(5000)=REPLICATE('a',5000); SELECT DATALENGTH(@part1),DATALENGTH(@part2),DATALENGTH(@ part1+@part2 );
Result - 5000 500, 8000
If one of the terms is of type MAX
, you will get the expected result
SELECT DATALENGTH(@part1),DATALENGTH(@part2),DATALENGTH(CAST(@part1 AS VARCHAR(MAX)) +@part2 );
The result is 5,000,000, 10,000
This is common in connection with
- string concatenation
- use of (older) functions returning
VARCHAR(8000)
as the previous maximum length - column definitions
UPDATE Same with CONCAT
SELECT DATALENGTH(@part1),DATALENGTH(@part2),DATALENGTH(CONCAT(@part1,@part2)); SELECT DATALENGTH(@part1),DATALENGTH(@part2),DATALENGTH(CONCAT(CAST(@part1 AS VARCHAR(MAX)),@part2));
source share