The problem turned out to be the NVARCHAR(4000)
type of @sql
, limiting its length to 4000 characters: the query got truncated at some random place after adding another long chunk to it.
DECLARE @sql NVARCHAR(MAX)
solves the problem, allowing a dynamic query of any size below 2GB.