Stored procedure executes dynamic splicing 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_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_data wd INNER JOIN sys_orginfo 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

Guess you like

Origin blog.csdn.net/GL666/article/details/131595963