[英]Converting SQL Query to Stored Procedure
How can I convert this to a stored procedure? 如何将其转换为存储过程?
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
I am not familiar with storedprocs. 我不熟悉storedprocs。
You need to figure out why you need a stored proc here, and where your inputted/outputted data goes. 您需要弄清楚为什么这里需要存储的proc,以及输入/输出数据的去向。 But Here's the framework for a stored-proc, in MySQL :
但是这是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();
Please see this example for a good reference - https://stackoverflow.com/a/10650323/763029 请参阅此示例以获取良好参考-https://stackoverflow.com/a/10650323/763029
If Sql Server you can use the CASE keyword. 如果是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
I think this syntax works.. 我认为这种语法有效。
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 ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.