Glad it finally worked out! 🙂
Did you notice how fast you had a tested solution once you provided ready to use data? 😉
I see you use the varchar(8000) instead of varchar(max). This save some meory/space ?
If you know that string length will not exceed 8k then you should use varchar(8000) (or even less) instead of varchar(max). Therewith SQL Server "knows" that the value will fit into one page and will store it directly in the data row. Otherwise it will need to store a pointer to the LOB storage space.
If you're unsure regarding performance influence I recommend you try both and compare the performance.