如何从存储过程检索表到数据表?

时间:2009-12-19 19:08:58

标签: c# .net asp.net sql-server ado.net

我创建了一个存储过程,以便为我返回一个表。

这样的事情:

create procedure sp_returnTable
body of procedure
select * from table
end

当我在前端调用此存储过程时,我需要编写哪些代码才能在数据表对象中检索它?

我写了类似下面的代码。我基本上想知道检索和存储表到datatable的对象。我的所有查询都在运行,但我不知道如何通过存储过程将表检索到数据表中

DataTable dtable = new DataTable();
cmd.Connection = _CONN;

cmd.CommandText = SPNameOrQuery;
cmd.CommandType = CommandType.StoredProcedure;

SqlDataAdapter adp = new SqlDataAdapter(cmd);
OpenConnection();
adp.Fill(dtTable);
CloseConnection();

此代码中的命令已与存储过程名称及其参数绑定。它会从存储过程返回一个数据表吗?

3 个答案:

答案 0 :(得分:46)

string connString = "<your connection string>";
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);
    }
}

Java Schools Example修改

答案 1 :(得分:5)

同时设置CommandText,并在Fill上致电SqlAdapter以检索DataSet中的结果:

var con = new SqlConnection();
con.ConnectionString = "connection string";
var com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "sp_returnTable";
var adapt = new SqlDataAdapter();
adapt.SelectCommand = com;
var dataset = new DataSet();
adapt.Fill(dataset);

(示例是为了清楚起见使用无参数构造函数;可以通过使用其他构造函数来缩短。)

答案 2 :(得分:0)

说明在调用存储过程时是否有人想要发送一些参数,

using (SqlConnection con = new SqlConnection(connetionString))
            {
                using (var command = new SqlCommand(storedProcName, con))
                {
                    foreach (var item in sqlParams)
                    {
                        item.Direction = ParameterDirection.Input;
                        item.DbType = DbType.String;
                        command.Parameters.Add(item);
                    }
                    command.CommandType = CommandType.StoredProcedure;
                    using (var adapter = new SqlDataAdapter(command))
                    {
                        adapter.Fill(dt);
                    }
                }
            }
相关问题