存储过程执行动态拼接sql
CREATE PROCEDURE getData(IN itemName varchar(100),IN year VARCHAR(50),IN org VARCHAR(100),OUT bal VARCHAR(100))
BEGIN
DECLARE itemKey VARCHAR(100) DEFAULT null;
SET @ret = 0; -- 初始化去除缓存
SELECT DISTINCT item_key into itemKey FROM sys_wa_item where item_name=itemName;
if (itemKey is not null) then
SET @sql_stmt = CONCAT('SELECT ifnull(sum(wd.',itemKey,'),0) into @ret FROM sys_wa_data wd INNER JOIN sys_org_info so on wd.fk_org_id=so.id WHERE 1=1 ');
if (year is not null) then
SET @sql_stmt=CONCAT(@sql_stmt,' and wd.year=''',year,'''');
end if;
if (org is not null) then
SET @sql_stmt=CONCAT(@sql_stmt,' and so.org_name=''',org,'''');
end if;
SET @sql_stmt = CONCAT(@sql_stmt,' GROUP BY wd.year');
PREPARE stmt FROM @sql_stmt;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
end if;
set bal=@ret;
END