create proc sp_PivotKolonlar(
@T1 datetime,
@T2 datetime
)
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),@T1,121) and convert(varchar(10),TARIH,121)<=convert(varchar(10),@T2,121) and ALACAK>0) AS DISTBAACIKLA
DECLARE @PVT nvarchar(max)
set @PVT=N'
SELECT * FROM (SELECT MUSKOD, BAACIKLA, ALACAK FROM ACARI where convert(varchar(10),TARIH,121)>='''+convert(varchar(10),@T1,121)+''' and convert(varchar(10),TARIH,121)<='''+convert(varchar(10),@T2,121)+''' ) AS PIVOTDATA
PIVOT ( SUM(ALACAK) FOR BAACIKLA IN ('+ @PivotKolonlar+')
) AS PIVOTTABLO
'
EXECUTE
(@PVT)
 


