-1

I need to loop for all records in my table , cose here is not working properly in my project "Auction web system" , I use web service here to check the status of product Periodically , and when the status is opened and data time is less to now , update the product and set its status to "closed". the code here work only for one row at the time ! I need to check for all rows at the same time.

    { string sql12 = "SELECT item_id FROM items Where status='opened' AND endDate<=@endate ";

    SqlCommand cmd12 = new SqlCommand(sql12, con);
    con.Open();
    cmd12.Parameters.AddWithValue("@endate", DateTime.Now);
    query = Convert.ToInt32(cmd12.ExecuteScalar());

    string sql123 = "UPDATE items SET status ='closed' WHERE item_id =@Item_ID";
    SqlCommand cmd21 = new SqlCommand(sql123, con);
    cmd21.Parameters.AddWithValue("@Item_ID", query);
    cmd21.ExecuteNonQuery();
    con.Close();
    CalculateWinningPrice(query);

   }
   public void CalculateWinningPrice(Int32 query)
   {

    string sql1 = "SELECT MAX(Bid_price) AS Expr1 FROM Bid WHERE (item_id = @Item_ID)";
    SqlCommand cmd1 = new SqlCommand(sql1, con);
    con.Open();
    cmd1.Parameters.AddWithValue("@Item_ID", query);
    Int32 max = Convert.ToInt32(cmd1.ExecuteScalar());

    SqlCommand cmd3 = new SqlCommand("SELECT user_id FROM Bid WHERE(Bid_price =(SELECT MAX(Bid_price) AS Expr1 FROM Bid AS BID_1 WHERE(item_id = @Item_ID)))", con);
    cmd3.Parameters.AddWithValue("@Item_ID", query);
    Int32 winner = Convert.ToInt32(cmd3.ExecuteScalar());

    SqlCommand cmd4 = new SqlCommand("SELECT name FROM items WHERE (item_id=@Item_ID)",con);
    cmd4.Parameters.AddWithValue("Item_ID", query);
    string product_name = Convert.ToString(cmd4.ExecuteScalar());

    GeneratePDF.create_pdf(product_name, Convert.ToDecimal(max).ToString("c"), DateTime.Now.ToString());

    SqlCommand cmd = new SqlCommand("INSERT INTO Winners VALUES(@item_id, @user_id,@win_price,@win_date)");
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@item_id", query);
    cmd.Parameters.AddWithValue("@user_id", winner);
    cmd.Parameters.AddWithValue("@win_price", max);
    cmd.Parameters.AddWithValue("@win_date", DateTime.Now);
    cmd.Connection = con;
    cmd.ExecuteNonQuery();
    con.Close();
   }
bashar it
  • 3
  • 4

2 Answers2

0

Get results into a datareader MSFT DOCU then wrap the rest of the code in

while(reader.Read()) 
{
    REST OF CODE 
}

This question might also help you. Reader Question

Community
  • 1
  • 1
Daniel E.
  • 2,029
  • 3
  • 22
  • 28
0

you can directly update your table by this query

UPDATE items SET status ='closed' WHERE item_id in(SELECT item_id FROM items Where status='opened' AND endDate<=@endate)