How can I retrieve a table from stored procedure to a datatable?

后端 未结 3 534
盖世英雄少女心
盖世英雄少女心 2020-12-05 04:26

I created a stored procedure so as to return me a table.

Something like this:

create procedure sp_returnTable
body of procedure
select * from table
e         


        
3条回答
  •  伪装坚强ぢ
    2020-12-05 05:00

    string connString = "";
    string sql = "name of your sp";
    
    using(SqlConnection conn = new SqlConnection(connString)) 
    {
        try 
        {
            using(SqlDataAdapter da = new SqlDataAdapter()) 
            {
                da.SelectCommand = new SqlCommand(sql, conn);
                da.SelectCommand.CommandType = CommandType.StoredProcedure;
    
                DataSet ds = new DataSet();   
                da.Fill(ds, "result_name");
    
                DataTable dt = ds.Tables["result_name"];
    
                foreach (DataRow row in dt.Rows) {
                    //manipulate your data
                }
            }    
        } 
        catch(SQLException ex) 
        {
            Console.WriteLine("SQL Error: " + ex.Message);
        }
        catch(Exception e) 
        {
            Console.WriteLine("Error: " + e.Message);
        }
    }
    

    Modified from Java Schools Example

提交回复
热议问题