将SQL查询转换为存储过程

时间:2015-11-16 01:20:42

标签: mysql stored-procedures

如何将其转换为存储过程?

select 
employee_name,
SUM(IF(cdr_call_type_code = 'CEL', cdr_charge_amount, 0)) as cell,
SUM(IF(cdr_call_type_code = 'NDD', cdr_charge_amount, 0)) as ndd,
SUM(IF(cdr_call_type_code = 'IDD', cdr_charge_amount, 0)) as idd,
SUM(cdr_charge_amount) as total
from cdr_employees

我不熟悉storedprocs。

3 个答案:

答案 0 :(得分:0)

你需要弄清楚为什么你需要一个存储过程,以及输入/输出数据的去向。但这是MySQL中存储过程的框架:

     drop procedure if exists simpleproc;

     DELIMITER //
      CREATE PROCEDURE simpleproc ()
      BEGIN

      select 
      employee_name,
      SUM(IF(cdr_call_type_code = 'CEL', cdr_charge_amount, 0)) as cell,
      SUM(IF(cdr_call_type_code = 'NDD', cdr_charge_amount, 0)) as ndd,
      SUM(IF(cdr_call_type_code = 'IDD', cdr_charge_amount, 0)) as idd,
      SUM(cdr_charge_amount) as total
      from cdr_employees;

      END//
     DELIMITER;

测试

call simpleproc();

请参阅此示例以获得一个很好的参考 - https://stackoverflow.com/a/10650323/763029

Stored procedure video source

答案 1 :(得分:0)

如果是Sql Server,则可以使用CASE关键字。

select 
employee_name,
CASE WHEN cdr_call_type_code = 'CEL' THEN SUM(cdr_call_type_code) ELSE 0 AS cell,
...from cdr_employees

答案 2 :(得分:0)

我认为这种语法有效..

DELIMITER $$

DROP PROCEDURE IF EXISTS `lcs_rdb`.`sp_CostCenterReport`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_CostCenterReport`()
BEGIN
        SET @sql = CONCAT("
            select 
            employee_name,
            SUM(IF(cdr_call_type_code = 'CEL', cdr_charge_amount, 0)) as cell,
            SUM(IF(cdr_call_type_code = 'NDD', cdr_charge_amount, 0)) as ndd,
            SUM(IF(cdr_call_type_code = 'IDD', cdr_charge_amount, 0)) as idd,
            SUM(cdr_charge_amount) as total
            from cdr_employees
            ");
  PREPARE stmt FROM @sql;
   EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
    END$$

DELIMITER ;