也許有人在看這個代碼將能夠告訴我爲什麼returnID總是0.我試圖從插入的記錄中檢索新的ID。SqlCommand返回值參數
public int AddToInventory(int PartID, int QtyOnHand, int SpokenFor, int LowOrderQty, int HighOrderQty, decimal LastBuyPrice,
decimal AvgBuyPrice)
{
ConfigDAL config = new ConfigDAL();
string connstr = config.GetConnString();
SqlConnection conn = new SqlConnection(connstr);
string query;
query = "INSERT INTO Inventory (PartID, QtyOnHand, SpokenFor, LowOrderQty, HighOrderQty, LastBuyPrice, "
+ "AvgBuyPrice, CreatedOn, CreatedBy, ModifiedOn, ModifiedBy) "
+ "Values (@PartID, @QtyOnHand, @SpokenFor, @LowOrderQty, @HighOrderQty, @LastBuyPrice, @AvgBuyPrice, "
+ "@CreatedOn, @CreatedBy, @ModifiedOn, @ModifiedBy)";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("@PartID", PartID);
cmd.Parameters.AddWithValue("@QtyOnHand", QtyOnHand);
cmd.Parameters.AddWithValue("@SpokenFor", SpokenFor);
cmd.Parameters.AddWithValue("@LowOrderQty", LowOrderQty);
cmd.Parameters.AddWithValue("@HighOrderQty", HighOrderQty);
cmd.Parameters.AddWithValue("@LastBuyPrice", LastBuyPrice);
cmd.Parameters.AddWithValue("@AvgBuyPrice", AvgBuyPrice);
cmd.Parameters.AddWithValue("@CreatedOn", DateTime.Now);
cmd.Parameters.AddWithValue("@CreatedBy", GlobalProp.UserName);
cmd.Parameters.AddWithValue("@ModifiedOn", DateTime.Now);
cmd.Parameters.AddWithValue("@ModifiedBy", GlobalProp.UserName);
cmd.Parameters.Add("@ID", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
int returnID = (int)cmd.Parameters["@ID"].Value;
return returnID;
}
記錄插入到表格中,但返回值不正確。我是否正確地做這件事?
感謝
你的方法告訴我,行cmd.ExecuteNonQuery()運行,我必須聲明標量變量「@ID」 – Ryan
我已更新我的答案'Declare @ID int;' – codingbiz