create   PROCEDURE sp_CariSatici_PivotRapor @carikodlar varchar(max),@saticilar varchar(max), @Tarih1 varchar(8), @Tarih2 varchar(8)  
-- sp_CariPivot '','','20210601','20210616'
as   
begin  
  DECLARE @PivotKolonlar VARCHAR(MAX)  
  SELECT @PivotKolonlar=    
    COALESCE (@PivotKolonlar +',['+CAST(BAACIKLA AS VARCHAR) +']',  
    '['+CAST(BAACIKLA AS VARCHAR)+']')  
    FROM (SELECT DISTINCT(BAACIKLA) FROM ACARI ) AS DISTBAACIKLA  
   
  DECLARE @PVT nvarchar(max)  
  
  declare @EkParam varchar(max)  
  set @EkParam=' where 1=1 '  
  if len(replace(@carikodlar,' ',''))>0  
    set @EkParam = @EkParam+'and C.MUSKOD in ('''+@carikodlar+''') '  
    
  if len(@Tarih1)+len(@Tarih2) >0  
  set @EkParam = @EkParam+ 'and TARIH between '''+@Tarih1 +''' and '''+@Tarih2+''' ';   
  
  if len(replace(@saticilar,' ',''))>0  
    set @EkParam=@EkParam+' and A.SaticiKodu in ('''+@saticilar+''')'  
      
  set @PVT=N'select * from (  
    select   C.MUSKOD,A.MUSADI,A.MUSIL,A.MUSILCE,A.SaticiAdi,C.BAACIKLA ,SUM(C.BORC-C.ALACAK) AS TUTAR from ACARI AS C  
    JOIN AMUSTERI AS A ON A.MUSKOD=C.MUSKOD '+@EkParam+'  
    GROUP BY  C.MUSKOD,A.MUSADI,A.MUSIL,A.MUSILCE,A.SaticiAdi,C.BAACIKLA) as PivotT  
    pivot ( Sum(TUTAR) for BAACIKLA in ('+@PivotKolonlar+') ) as pvt  
    '  
   EXECUTE (@PVT)   
end  