无法检索存储过程的结果

时间:2014-01-12 16:55:34

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

我有一个存储过程,它以我想要检索的数据的select语句结束。我似乎无法在C#代码中实际填充DataTable。没有例外,只是一个空的DataTable(甚至不是null!)。

我做错了什么?以下代码是否准确?

DataTable dt = new DataTable();
    try
    {
        using (SqlConnection conn = new SqlConnection(connString))
        using (SqlCommand command = new SqlCommand(ProcName, conn)
        {
            CommandType = CommandType.StoredProcedure
        })
        {
            conn.Open();
            command.ExecuteScalar(); 
            SqlDataAdapter da = new SqlDataAdapter(command);
            da.Fill(dt);
            da.Dispose();
            conn.Close();
        }
    }
    catch (Exception ex)
    {
    }
    finally
    {
    }
    return dt; 

2 个答案:

答案 0 :(得分:2)

using(SqlConnection conn = new  SqlConnection(connString))
using(SqlCommand command = new SqlCommand(ProcName, conn))
using(SqlDataAdapter da = new SqlDataAdapter(command))
{
  command.CommandType = CommandType.StoredProcedure;
  da.Fill(dt);
}

答案 1 :(得分:0)

SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;

cmd.CommandText = "SELECT * FROM Customers";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;

sqlConnection1.Open();

reader = cmd.ExecuteReader();  <--- no executescalar 
// Data is accessible through the DataReader object here.

sqlConnection1.Close();