将插入的值保存到c#变量中

时间:2014-04-09 21:25:02

标签: c# sql-server-2008 scope

我想通过添加最后插入的值来更新我的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();
            }


        }


    }

请告诉我如何实现这一目标?

0 个答案:

没有答案