MySQL中這樣建立存貯過程(procedure)

  1. DROP PROCEDURE IF EXISTS sp_unit_by_sec_class;
  2. delimiter //
  3. CREATE PROCEDURE sp_unit_by_sec_class (DICT_ID INT,ORDER_BY INT )
  4. BEGIN
  5.     IF (ORDER_BY = 1 )
  6.         THEN
  7.             SELECT * FROM
  8.             (
  9.                 SELECT e. unit_id,e. unit_price,e. cr_date,e. USER_NAME,e. unit_memo,e. unit_status
  10.                 FROM t_units e
  11.                 WHERE e. dict_id = DICT_ID
  12.                
  13.                 UNION
  14.                 SELECT c. unit_id,d. drop_fee-d. grow_fee,d. drop_date,d. USER_NAME,drop_memo,c. unit_status
  15.                 FROM t_units c
  16.                 RIGHT JOIN t_drop d ON c. unit_id = d. unit_id
  17.                 WHERE c. dict_id = DICT_ID
  18.  
  19.                 UNION
  20.                 SELECT a. unit_id,b. grow_fee,b. grow_date,b. USER_NAME,b. grow_memo, 2
  21.                 FROM t_units a
  22.                 RIGHT JOIN t_grow b ON a. unit_id = b. unit_id
  23.                 WHERE a. dict_id = DICT_ID
  24.             ) t1 ORDER BY 1, 3;
  25.         ELSE
  26.             SELECT * FROM
  27.             (
  28.                 SELECT e. unit_id,e. unit_price,e. cr_date,e. USER_NAME,e. unit_memo,e. unit_status
  29.                 FROM t_units e
  30.                 WHERE e. dict_id = DICT_ID
  31.                
  32.                 UNION
  33.                 SELECT c. unit_id,d. drop_fee-d. grow_fee,d. drop_date,d. USER_NAME,drop_memo,c. unit_status
  34.                 FROM t_units c
  35.                 RIGHT JOIN t_drop d ON c. unit_id = d. unit_id
  36.                 WHERE c. dict_id = DICT_ID
  37.  
  38.                 UNION
  39.                 SELECT a. unit_id,b. grow_fee,b. grow_date,b. USER_NAME,b. grow_memo, 2
  40.                 FROM t_units a
  41.                 RIGHT JOIN t_grow b ON a. unit_id = b. unit_id
  42.                 WHERE a. dict_id = DICT_ID
  43.             ) t1 ORDER BY 3, 1;
  44.     END IF;
  45. END
  46. ;
  47. //
  48. delimiter ;