In this article I will explain with an example, how to solve the following error in SQL Server.
STRING_AGG aggregation result exceeded the limit of 8000 bytes. Use LOB types to avoid result truncation
STRING_AGG aggregation result exceeded the limit of 8000 bytes
 
 

Database

I have made use of the following table Customers with the schema as follows.
STRING_AGG aggregation result exceeded the limit of 8000 bytes
 
I have already inserted few records in the table.
STRING_AGG aggregation result exceeded the limit of 8000 bytes
 
Note: You can download the database table SQL by clicking the download link below.
            Download SQL file
 
 

Cause

The above error is caused when the length of the concatenated string exceeds the length of the column.
 
 

Solution

The solution to this problem is to make use of maximum value just as VARCHAR(MAX) OR NVARCHAR(MAX) when concatenating column data.
SELECT STRING_AGG(CAST(CustomerId AS VARCHAR(MAX)),  ',')
FROM Customers
 
 

Screenshot

STRING_AGG aggregation result exceeded the limit of 8000 bytes