You need to fix this:
SELECT @listCol = STUFF(( SELECT distinct '], [' + [size]
FROM #t
FOR
XML PATH('')
), 1, 2, '') + ']'
To return the columns in the right order. You might have to do something like this instead of using DISTINCT
:
SELECT [size]
FROM #t
GROUP BY [size]
ORDER BY MIN(BucketNum)