select B.Code, DealerID into #t from DealerBrand DB inner join Brand B on DB.BrandID = B.ID
SELECT
DealerID,
Brands = STUFF((SELECT ', ' + B.Code FROM #t b WHERE b.DealerID = a.DealerID FOR XML PATH('')), 1, 2, '')
into #DealerBrand FROM #t a
GROUP BY DealerID
SELECT
DealerID,
Brands = STUFF((SELECT ', ' + B.Code FROM #t b WHERE b.DealerID = a.DealerID FOR XML PATH('')), 1, 2, '')
into #DealerBrand FROM #t a
GROUP BY DealerID