我应该如何在我的SQL查询中实现和IF语句?

时间:2013-01-10 12:28:37

标签: mysql sql c#-4.0

这是我的代码:

string cmdstr = "UPDATE itemsordered i " +
                "INNER JOIN"+
                    "(  SELECT itemsOrdered_quantity, itemsOrdered_ID,  "+
                            "IF itemsOrdered_quantity = '"+quantityTxtBox.Text+"' SELECT 'EQUAL' "+
                            "IF itemsOrdered_quantity < '" + quantityTxtBox.Text + "' SELECT 'LESS' " +
                            "IF itemsOrdered_quantity > '" + quantityTxtBox.Text + "' SELECT '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 " +
               "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 + "' AND res.r = 'EQUAL'";
cmd = new MySqlCommand(cmdstr, db.mycon);
cmd.ExecuteNonQuery();

MessageBox.Show("ITEM RESTOCKED!");

我真正想要做的是,如果itemsOrdered_quantity等于quantityTxtBox中的值,那么它会通过在s.stock_quantity上添加金额来更新itemsOrdered_quantity到目前的数额。

我还想提出其他IF条款。但我想首先解决这个难题。

它在cmd.ExecuteNonQuery上返回一个错误,并指向我的SQL字符串'靠近'我的IF语句。

3 个答案:

答案 0 :(得分:1)

MySQL使用CASE语句,基本语法为:

SELECT CASE WHEN a = b THEN c ELSE d END CASE

您也可以

SELECT CASE WHEN a = b THEN c 
            WHEN a > b THEN e
            ELSE d END CASE

答案 1 :(得分:0)

是的,你可以使用if statment

   SELECT IF(1<2,'yes','no');
   //output  -> 'yes'
  //if 1<2 is true then return  `yes` if not true return `no`

答案 2 :(得分:0)

select (case when  itemsOrdered_quantity= '"+quantityTxtBox.Text+"'then 'EQUAL' else (case when itemsOrdered_quantity<  '"+quantityTxtBox.Text+"' then 'LESS' else  'MORE' end ) end) as r from itemsordered