c# - 如何将表从存储过程检索到数据表?

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

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

像这样:

create procedure sp_returnTable
body of procedure
select * from table
end

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

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

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

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

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

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

最佳答案

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

关于c# - 如何将表从存储过程检索到数据表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1933855/

相关文章:

c# - 使用 asp.net 将服务器证书导入 Keystore 以验证请求来自受信任的服务器

c# - 如何通过 HTTP 请求发送和发送电子邮件

java - 将 Java 与 .NET 集成?

asp.net - Razor 应用程序中出现错误 "Index was out of range"

c# - 使用部分类进行验证?

c# - 使用 rowdatabound 计算列数

c# - 如何使用 ComboBox (WPF) "Fill"GridViewColumn?

c# - 不同模型类的组合?

c# - 进程间消息广播

.net - 我是否需要始终在异步代码流中已有的方法中使用 async/await?