-1

正如上面的问题所说,我的查询中有一个 IF 子句。现在我想根据 IF 子句的结果进行更新。任何想法我怎么能做到这一点?

这是我的代码:

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!");

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

4

2 回答 2

2

代替IF ... BEGIN, 使用CASE表达式。删除BEGIN ... IFand 只有一个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,
   ....
...
于 2013-01-10T14:05:48.750 回答
2

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

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

于 2013-01-10T14:06:02.547 回答