Someone on the forum would be able to suggest the changes you need to make if you post (simplified) sample code that demonstrates the problem. It is hard to guess without that. For example, see the following:
DECLARE @s0 NVARCHAR(4000) = REPLICATE('A',4000);
DECLARE @s1 NVARCHAR(MAX) = REPLICATE (@s0,4);
-- returns 4000 as length even though @s1 is declared as nvarchar(max)
-- this is expected behavior.