create or alter  proc sp_PivotKolonlar( @Tarih1 datetime='20000101', @Tarih2 datetime='20250101'  )    
as    
DECLARE @PivotKolonlar VARCHAR(MAX)    
SELECT @PivotKolonlar=      
COALESCE (@PivotKolonlar +',['+CAST(BAACIKLA AS VARCHAR) +']',    
'['+CAST(BAACIKLA AS VARCHAR)+']')    
FROM (SELECT DISTINCT(BAACIKLA) FROM ACARI where convert(varchar(10),TARIH,121)>=convert(varchar(10),@Tarih1,121) and convert(varchar(10),TARIH,121)<=convert(varchar(10),@Tarih2,121) ) AS DISTBAACIKLA    
DECLARE @PVT nvarchar(max)    
set @PVT=N'    
SELECT * FROM (SELECT A.MUSKOD,M.MUSADI,ROUND(M.MUSBAKIYE,0) BAKIYE, BAACIKLA, (A.BORC-A.ALACAK) TUTAR FROM ACARI A ,V_AMUSTERI M  where A.MUSNO=M.MUSNO AND
convert(varchar(10),TARIH,121)>='''+convert(varchar(10),@Tarih1,121)+''' and 
convert(varchar(10),TARIH,121)<='''+convert(varchar(10),@Tarih2,121)+''' ) AS PIVOTDATA    
PIVOT ( SUM(TUTAR)   FOR BAACIKLA IN ('+ @PivotKolonlar+')    
) AS PIVOTTABLO    ORDER BY MUSADI
'    
EXECUTE  (@PVT)