DECLARE @Query AS NVARCHAR (MAX) ,@ColumnName AS NVARCHAR (MAX)
SELECT @ColumnName = ISNULL(@ColumnName + ',', '') + QUOTENAME(Code)
FROM (
SELECT DISTINCT Code
FROM dbo.TABLE
WHERE Status = 1
) AS Branch
ORDER BY Code ASC
SET @Query = N'
SELECT Code
, Name
, ' + @ColumnName + '
, Total
FROM (
-----
-----
-----
) AS j PIVOT(SUM(Qty) FOR Branch IN (' + @ColumnName + ')) AS Branch '