SqlCommand的返回值参数 [英] SqlCommand return value parameter
本文介绍了SqlCommand的返回值参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
也许别人看着这个code将能告诉我为什么returnID始终是0我试图从插入的记录检索新的ID。
Maybe someone else looking at this code will be able to tell me why the returnID is always 0. I am attempting to retrieve the new ID from the inserted record.
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;
}
该记录被插入到表罚款,但返回的值是不正确的。我是否在做正确吗?
The record gets inserted to the table fine, but the return value is not right. Am I doing this correctly?
感谢
推荐答案
有没有你在哪里设置的ID,所以你可以期待值改变。你要做到这一点与
There is no where you were setting the ID, so you can expect the value to change. You have to do that with
Select @ID = @Scope_Identity() -- If ID column is an Identity column
或
Select @ID = @SomeGeneratedValue
试试这个
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);"
+ " Declare @ID int;"
+ " Select @ID = Scope_Identity()";
这篇关于SqlCommand的返回值参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文