如何使用存储过程数据透视中的参数填充gridview

时间:2017-06-01 00:52:55

标签: c# asp.net sql-server gridview pivot

我是新来的,任何人都可以帮我解决这个问题,一直在尝试很多但是无法通过。我正在尝试使用带有参数的存储过程使用pivot来填充gridview,在我的where子句中,当我直接分配值然后它工作正常但是当我使用参数以便用户可以选择然后它会抛出错误。提前谢谢。

我的程序:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[GetMarksheetByExamId]
    (@SubjectId INT)
AS
    DECLARE @cols AS NVARCHAR(MAX),
            @query  AS NVARCHAR(MAX)

    SELECT @cols = STUFF((SELECT ',' + QUOTENAME(Subjects) 
                          FROM SMarksheet
                          GROUP BY Subjects
                          -- ORDER BY Id
                          FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')

    SET @query = 'SELECT SubjectId, StudentName ' + @cols + ' FROM 
             (SELECT SubjectId, StudentName, Subjects, TotalM 
              FROM SMarksheet  
              WHERE SubjectId = @SubjectId) x
             PIVOT
                 (MAX(TotalM)
                  FOR Subjects IN (' + @cols +')) p '

    EXEC sp_executesql @query;

我的网格视图:

<table border="1" width="60%" align="center">
    <tr>
        <td align="center">
            <asp:TextBox ID="txt_Id" runat="server" AutoPostBack="true">1</asp:TextBox>
            <br />
            <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
        </td>
    </tr>
    <tr>
        <td>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">
            </asp:GridView>
        </td>
    </tr>
</table>

代码背后:

protected void Button1_Click(object sender, EventArgs e)
{
    DataSet ds = new DataSet();

    using (SqlConnection con = new SqlConnection(connStr))
    {
        using (SqlCommand command = new SqlCommand())
        {
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "GetMarksheetByExamId";
            command.Connection = con;

            //  command.Parameters.AddWithValue("@SubjectId", b);
            command.Parameters.Add(new SqlParameter("@SubjectId", txt_Id.Text));

            con.Open();

            SqlDataAdapter a = new SqlDataAdapter(command);
            a.Fill(ds);
        }
    }

    GridView1.DataSource = ds;
    GridView1.DataBind();
}

1 个答案:

答案 0 :(得分:0)

看起来您的变量分配在动态查询中。您需要更改@Query赋值,如下所示:

set @query = 'SELECT SubjectId, StudentName ' + @cols + ' from 
         (
            select SubjectId, StudentName, Subjects, TotalM 
            from SMarksheet  
            where SubjectId=@SubId


        ) x
        pivot 
        (
            max(TotalM)
            for Subjects in (' + @cols +')
        ) p '

exec sp_executesql @query, @SubId = @SubjectId;

你可以像上面那样传递subject作为参数