I write pivot dynamic query to get record
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
SELECT @ColumnName = ISNULL(@ColumnName + ',','')+ QUOTENAME(FeesDetail) FROM (SELECT DISTINCT FeesDetail FROM tblFeesDetail where Class=@CId and Section=@SId) AS FeesHead
SET @DynamicPivotQuery = ';WITH CTE AS(SELECT dis.AdmissionNo,ReferenceNo,dis.Year,dis.Class,dis.Section,SName,FName,ParentID,FeesDetail,Amount,Discount,ISNULL(DisAmount,0) - ISNULL(Discount,0) as [ActualFees] FROM tblFeesDetail as fd inner join tblDiscount as dis on fd.Class=dis.Class and fd.Section=dis.Section inner join tblStdReg as sr on dis.AdmissionNo=sr.AdmissionNo and Active_Status = ''Active'' )
SELECT AdmissionNo,ReferenceNo,Year,Class,Section,SName,FName,ParentID,'+@ColumnName+',Discount,ActualFees FROM CTE
PIVOT (MAX(Amount)
FOR FeesDetail IN('+@ColumnName+')) p
where Class=(''Five'') and Section=(''A'') '
EXEC(@DynamicPivotQuery);
this query is working fine and showing output
Now I want to get class and section wise data of student. I used following code but nothing is shown how to fix it
protected void ddlSection_SelectedIndexChanged(object sender, EventArgs e)
{
this.BindGridSec();
}
protected void BindGridSec()
{
con = new SqlDbConnect();
con.SqlQuery(@"DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
SELECT @ColumnName = ISNULL(@ColumnName + ',','')+ QUOTENAME(FeesDetail) FROM (SELECT DISTINCT FeesDetail FROM tblFeesDetail where Class=@CId and Section=@SId) AS FeesHead
SET @DynamicPivotQuery = ';WITH CTE AS(SELECT dis.AdmissionNo,ReferenceNo,dis.Year,dis.Class,dis.Section,SName,FName,ParentID,FeesDetail,Amount,Discount,ISNULL(DisAmount,0) - ISNULL(Discount,0) as [ActualFees] FROM tblFeesDetail as fd inner join tblDiscount as dis on fd.Class=dis.Class and fd.Section=dis.Section inner join tblStdReg as sr on dis.AdmissionNo=sr.AdmissionNo and Active_Status = ''Active'' )
SELECT AdmissionNo,ReferenceNo,Year,Class,Section,SName,FName,ParentID,'+@ColumnName+',Discount,ActualFees FROM CTE
PIVOT (MAX(Amount)
FOR FeesDetail IN('+@ColumnName+')) p
where Class=(''+@CId+'') and Section=(''+@SId+'') '
EXEC(@DynamicPivotQuery);");
con.Cmd.Parameters.Add(new SqlParameter("@CId", ddlClass.SelectedItem.ToString()));
con.Cmd.Parameters.Add(new SqlParameter("@SId", ddlSection.SelectedItem.ToString()));
adapt.SelectCommand = con.Cmd;
adapt.Fill(sTable);
if (sTable.Rows.Count > 0)
{
GridView1.Visible = true;
GridView1.DataSource = sTable;
GridView1.DataBind();
lblSTotal.Text = GridView1.Rows.Count.ToString();
}