我想通过添加最后插入的值来更新我的stock.quantity
属性。但我在if块中收到错误Use of unassigned local variable 'qty'
。我无法将其初始化为0,因为每次调用manageStock
时,它都会初始化为0.
这是我的代码
public static void manageStock(CompanyStock stock)
{
///// Check if record exists/////////
cmd = new SqlCommand("select count(*) from tblStock where prodName=@prodName", con);
cmd.Parameters.AddWithValue("@prodName", stock.prodName);
int count;
int qty;
try
{
con.Open();
count = (Int32)cmd.ExecuteScalar(); //returns null if doesnt exist
}
finally {
con.Close();
}
if (count > 0)
{
stock.quantity += qty;
cmd = new SqlCommand("update tblStock set quantity = @quantity where prodName=@prodName", con);
cmd.Parameters.AddWithValue("@prodName", stock.prodName);
cmd.Parameters.AddWithValue("@quantity", stock.quantity);
}
else
{
qty = stock.quantity;
cmd = new SqlCommand("insert into tblStock(prodName,quantity) values (@prodName, @quantity)", con);
cmd.Parameters.AddWithValue("@prodName",stock.prodName);
cmd.Parameters.AddWithValue("@quantity",stock.quantity);
}
try
{
con.Open();
cmd.ExecuteNonQuery();
}
finally
{
con.Close();
}
}
}
请告诉我如何实现这一目标?