 <p>don't look for bug free query here because you haven' provided enough info and sample data. So start pointing out one be one,</p> <pre><code>Declare @i varchar='Jan-13' declare @upto int=11 Declare @FromDate date=convert(varchar(12),'1-'+'Jan-13',120) Declare @Todate date =dateadd(month,@upto,@FromDate) select convert(char(6),@FromDate,107) ,@ToDate Declare @StringDate varchar(2000)='' select @StringDate= stuff((select ','+'['+convert(char(6),ODLN.DocDate ,107)DocDate+']' from ODLN inner join DLN1 on odln.DocEntry = ODLN.DocEntry where ODLN.DocDate between between @FromDate and @Todate for xml path('')),1,1,'') --@StringDate will have value like [Jan-13],[Dec-12] and so on Declare @qry varchar(max)='' set @qry='select CardName,'+@StringDate+' from (select CardName,CardCode ,DLN1.Quantity,convert(char(6),ODLN.DocDate ,107)DocDate from ODLN inner join DLN1 on odln.DocEntry = ODLN.DocEntry where ODLN.DocDate between between '+@FromDate+' and '+@Todate+')tbl pivot( max(Quantity) for DocDate in('+@StringDate+'))pvt' exec @qry </code></pre>