如何根据查询中IF语句的结果进行更新?
本文关键字:结果 更新 语句 何根 查询 IF | 更新日期: 2023-09-27 17:51:16
正如上面的问题所说,我的查询中有一个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
子句附近有错误。
用CASE
代替IF ... BEGIN
。删除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,
....
...
我会拿出IF
块,并有2个不同的SQL语句。
将不同的IF
条件放在每个查询的WHERE
子句中