如何从存储过程

时间:2017-12-25 14:27:09

标签: c# sql-server

我正在尝试使用参数执行存储过程,并将结果导入DataTable;但执行后,我明白了:

this is the screen

我可以IDataRecord但我不能IDataReader - 为什么?我错过了什么?感谢

public DataTable ExecuteProcedureTest(string storedProcedure, Dictionary<Filter, object> filterValue)
{
    var parameters = GetParams(filterValue);

    var sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["testconn"].ConnectionString);

    var cmd = sqlConnection.CreateCommand(); 

    SqlDataReader reader;
    IDataReader dataReader;
    IDataRecord[] dataRecords;

    var table = new DataTable();

    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = storedProcedure;

    foreach (var item in parameters)
    {
        cmd.Parameters.Add(item);
    }

    try
    {
        sqlConnection.Open();
        reader = cmd.ExecuteReader();

        dataRecords = reader.OfType<IDataRecord>().ToArray();
        table.Load(reader);
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        sqlConnection.Dispose();
    }

    //var count = dataRecords.Count();
    return table;
} 

1 个答案:

答案 0 :(得分:0)

如果您的目标是从DataTable填充SqlCommand,请使用SqlDataAdapter代替SqlDataReader。这是一个方便的扩展方法:

public static class SqlExtensions
{
    public static DataTable ExecuteDataTable(this SqlCommand command)
    {
        DataTable table = new DataTable();
        using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
        {
            dataAdapter.Fill(table);
        }
        return table;
    }
}

然后从你的代码中你可以像这样使用它:

try
{
    sqlConnection.Open();
    table = cmd.ExecuteDataTable();
}
finally
{
    sqlConnection.Dispose();
}