Hardik,
Unfortunately, the length of your string is just 8000 only. Try the following
DECLARE @p VARCHAR(MAX)
SELECT @p = REPLICATE('a', 5000)
SELECT LEN(@p)
-- RETURNS 5000
SELECT @p = REPLICATE('a', 5000) + REPLICATE('b', 5000)
SELECT LEN(@p)
-- You would expect to see 10,000
-- But result is 8000
The reason for this behaviour is that, each of the REPLICATE() function above returns a VARCHAR(8000) value. The result of two operations involving VARCHAR(8000) data type will only be VARCHAR(8000).
To get the desired result, you should force the REPLICATE() function to return a VARCHAR(MAX) value. This can be done as shown in the example below.
SELECT @p = REPLICATE(CAST('a' AS VARCHAR(MAX)), 5000) + REPLICATE('b', 5000)
SELECT LEN(@p)
-- RETURNS 10,000
In the above example, the first REPLICATE() function returns a VARCHAR(MAX) value. An operation that involves a VARCHAR(MAX) and VARCHAR(8000) values will result in VARCHAR(MAX) output.
You might have also received the same result if you attempted the original example in two steps. See this example:
DECLARE @p VARCHAR(MAX)
SELECT @p = REPLICATE('a', 5000)
SELECT @p = @p + REPLICATE('b', 5000)
SELECT LEN(@p)
-- RETURNS 10,000
Interesting, isn't it?
:-)
commented on May 29 2012 6:06AM