1

我有以下代码:

public static void executeStoredProcedure(SqlCommand sp)
{
           SqlConnection conn = new SqlConnection();
           conn.ConnectionString=Connection.getConnection();
           conn.Open();
           sp.CommandType = CommandType.StoredProcedure;
           sp.Connection = conn;
           sp.ExecuteNonQuery();
           conn.Close();
}

此代码执行存储过程。

但我的存储过程是

Create procedure [dbo].[selectAllItems]
(@ItemCode varchar(50) )
as
begin
    select * from Item where ItemCode  = @ItemCode
end

它将返回行,但如何在上面的 c# 代码中获得此结果

4

3 回答 3

2

您需要使用 aSqlDataReader来读取存储过程返回的结果集:

using (SqlConnection conn = new SqlConnection(Connection.getConnection()))
using (SqlCommand sp = new SqlCommand("dbo.selectAllItems", conn))
{
       sp.CommandType = CommandType.StoredProcedure;
       sp.Parameters.Add("@ItemCode", SqlDbType.Int).Value = your-item-code-value-here;

       conn.Open();

       using (SqlDataReader rdr = sp.ExecuteReader())
       {
          while (rdr.Read())
          {
             // read the values from the data reader, e.g.
             // adapt to match your actual query! You didn't mentioned *what columns*
             // are being returned, and what data type they are
             string colValue1 = rdr.GetString(0);
             int colValue2 = rdr.GetInt(1);
          }
       }

       conn.Close();
}

使用从 中读取的这些值SqlDataReader,您可以例如创建一个对象类型并设置其属性 - 或类似的东西 - 完全取决于您想要做什么。

当然:使用像实体框架这样的 ORM 将使不必编写大量此类代码 - EF 会自动为您处理这些。

于 2013-06-08T12:26:00.060 回答
1

您需要将参数解析为您的存储过程,如下所示

sp.Parameters.AddWithValue("@ItemCode", itemcode);

示例代码

public DataTable SelectAllItems(string itemCode)
{
    DataTable dt = new DataTable();
    using (SqlConnection conn = new SqlConnection(Connection.getConnection()))
    using (SqlCommand cmd = new SqlCommand("selectAllItems", conn))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@ItemCode", itemCode);
        conn.Open();

        using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
        {
            adapter.Fill(dt);
        }

    }
    return dt;
}
于 2013-06-08T12:27:42.017 回答
0

您可以使用 SQL 数据阅读器检查以下示例。

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.read.aspx

于 2013-06-08T12:27:16.000 回答