[英]How to get result from stored procedure and save result in a class attributes
我有以下代碼:
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#代碼中獲得此結果
您需要使用SqlDataReader
來讀取存儲過程返回的結果集:
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會處理這個給你-自動的。
您需要將參數解析為您的存儲過程,如下所示
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.