Return Result from Select Query in stored procedure to a List

前端 未结 8 2058
猫巷女王i
猫巷女王i 2021-01-01 10:10

I\'m writing a stored procedure that currently contains only a SELECT query. It will be expanded to do a number of other things, which is why it has to be a sto

8条回答
  •  北荒
    北荒 (楼主)
    2021-01-01 10:26

    In stored procedure, you just need to write the select query like the below:

    CREATE PROCEDURE TestProcedure
    AS
    BEGIN
        SELECT ID, Name 
        FROM Test
    END
    

    On C# side, you can access using Reader, datatable, adapter.

    Using adapter has just explained by Susanna Floora.

    Using Reader:

    SqlConnection connection = new SqlConnection(ConnectionString);
    
    command = new SqlCommand("TestProcedure", connection);
    command.CommandType = System.Data.CommandType.StoredProcedure;
    connection.Open();
    SqlDataReader reader = command.ExecuteReader();
    
    List TestList = new List();
    Test test = null;
    
    while (reader.Read())
    {
        test = new Test();
        test.ID = int.Parse(reader["ID"].ToString());
        test.Name = reader["Name"].ToString();
        TestList.Add(test);
    }
    
    gvGrid.DataSource = TestList;
    gvGrid.DataBind();
    

    Using dataTable:

    SqlConnection connection = new SqlConnection(ConnectionString);
    
    command = new SqlCommand("TestProcedure", connection);
    command.CommandType = System.Data.CommandType.StoredProcedure;
    connection.Open();
    
    DataTable dt = new DataTable();
    
    dt.Load(command.ExecuteReader());
    gvGrid.DataSource = dt;
    gvGrid.DataBind();
    

    I hope it will help you. :)

提交回复
热议问题