MySQL存储过程中是否有三元运算符?

时间:2013-12-03 13:46:32

标签: mysql sql stored-procedures mysql5

SQL(MySQL)是否支持三元运算符?

我有这个SQL:

CREATE TEMPORARY TABLE SalesTbl (
    CTR int primary key auto_increment, 
    VRNOA VARCHAR(50), 
    DESCRIPTION VARCHAR(50), 
    INQTY INT, 
    OUTQTY INT, 
    ETYPE VARCHAR(50), 
    RTotal DECIMAL(19,2)
);

INSERT INTO SalesTbl
SELECT 0, stockmain.VRNOA AS 'VRNOA', Item.description as 'DESCRIPTION', 
       qty as 'QTY', Stockmain.etype 'ETYPE', null 
FROM StockMain 
     INNER JOIN StockDetail on StockMain.stid = StockDetail.stid 
     INNER JOIN ITEM on StockDetail.item_id = Item.item_id 
WHERE StockDetail.item_id = 6 
AND   StockMain.vrdate BETWEEN '2010/10/02' AND '2013/12/02' 
ORDER BY Qty;

可以在MySQL中做这样的事情吗?

(QTY < 0) ? QTY : 0

如果QTY小于0,则使用QTY,否则使用0。

2 个答案:

答案 0 :(得分:1)

您需要CASE语句(或者有IF语句,但CASE是许多数据库的标准),它返回第一个真实条件的表达式。
http://dev.mysql.com/doc/refman/5.0/en/case.html

CREATE TEMPORARY TABLE SalesTbl (CTR int primary key auto_increment, 
                                 VRNOA VARCHAR(50), 
                                 DESCRIPTION VARCHAR(50), 
                                 INQTY INT, 
                                 OUTQTY INT, 
                                 ETYPE VARCHAR(50), 
                                 RTotal DECIMAL(19,2));

INSERT INTO SalesTbl

SELECT 
  0, 
  stockmain.VRNOA AS 'VRNOA', 
  Item.description as 'DESCRIPTION', 
  qty as 'QTY', 
  CASE WHEN qty<0 then qty end as InQTY, 
  CASE WHEN qty>0 then qty end as OutQTY,
  Stockmain.etype 'ETYPE', 
  null 
 FROM StockMain 
INNER JOIN StockDetail on StockMain.stid = StockDetail.stid 
INNER JOIN ITEM on StockDetail.item_id = Item.item_id 
WHERE StockDetail.item_id = 6 
AND StockMain.vrdate BETWEEN '2010/10/02' AND '2013/12/02' 
ORDER BY Qty;

答案 1 :(得分:1)

MySQL中没有专门的三元运算符,但您可以像这样接近它:

delimiter //
DROP PROCEDURE IF EXISTS `foobar`//
CREATE PROCEDURE `foobar`()
BEGIN
  declare romulan int default 0;
  set romulan = 1;

  select if (romulan = 1, 52, 99) into romulan;

  select romulan;
END//

像这样运行:

mysql> call foobar(3);

打印:

+---------+
| romulan |
+---------+
|      52 |
+---------+
1 row in set (0.00 sec)

因此如果romulan为1,则romulan变为52,否则romulan变为99.