如何根据查询中的IF语句结果进行更新?

时间:2013-01-10 13:59:17

标签: c# mysql if-statement

如上所述,我的查询中有一个IF子句。现在我想根据IF子句的结果进行UPDATE。我有什么想法可以做到这一点吗?

这是我的代码:

string cmdstr = "UPDATE itemsordered i " +
                "INNER JOIN" +
                    "(  SELECT itemsOrdered_quantity, itemsOrdered_ID,  " +
                            "CASE WHEN itemsOrdered_quantity = '" + quantityTxtBox.Text + "' THEN 'EQUAL' " +
                                 "WHEN itemsOrdered_quantity < '" + quantityTxtBox.Text + "' THEN 'LESS' " +
                                 "WHEN itemsOrdered_quantity > '" + quantityTxtBox.Text + "' THEN 'MORE'  " +
                        "END AS r " +
                        "FROM itemsordered " +
                    ") res ON i.itemsOrdered_ID = res.itemsOrdered_ID " +
               "INNER JOIN stocksdb s ON s.stock_ID = i.stock_ID " +
               "IF (res.r = 'EQUAL') " +
               "BEGIN " +
               "SET s.stock_quantity = (s.stock_quantity + i.itemsOrdered_quantity), " +
                   "s.stock_dateUpdated = '" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "', " +
                   "i.itemsOrdered_status = 'RECEIVED', " +
                   "i.itemsOrdered_dateReceived = '" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "' " +
                   "WHERE i.itemsOrdered_ID = '" + idTxtBox.Text + "' " +
               "END " +
               "IF (res.r = 'LESS') " +
               "BEGIN " +
               "SET s.stock_quantity = (s.stock_quantity + i.itemsOrdered_quantity), " +
                   "s.stock_dateUpdated = '" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "', " +
                   "i.itemsOrdered_quantity = (i.itemsOrdered_quantity - " + quantityTxtBox.Text + "), " +
                   "i.itemsOrdered_dateReceived = '" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "' " +
                   "WHERE i.itemsOrdered_ID = '" + idTxtBox.Text + "' " +
               "END";
cmd = new MySqlCommand(cmdstr, db.mycon);
cmd.ExecuteNonQuery();

MessageBox.Show("ITEM RESTOCKED!");

它会在cmd.ExecuteNonQuery()上返回错误,并说第一个IF子句附近有错误。

2 个答案:

答案 0 :(得分:2)

使用IF ... BEGIN表达式而不是CASE。删除BEGIN ... IF并且只有一个SET子句。类似的东西:

SET s.stock_quantity = CASE 
                         WHEN res.r = 'EQUAL' THEN s.stock_quantity + i.itemsOrdered_quantity
                         ELSE ...
                       END,
   s.stock_dateUpdated = CASE 
                           WHEN res.r = 'EQUAL' THEN ...
                           ELSE ...
                         END,
   ....
...

答案 1 :(得分:2)

我会取出IF块,并有两个不同的SQL语句。

将不同的IF条件放在每个查询的WHERE子句中。