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
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
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