将列名称作为参数传递并调用

时间:2015-10-06 10:34:48

标签: mysql

CREATE PROCEDURE data1 (IN v_dt2 VARCHAR(256) , v_col2 VARCHAR(256),col2 VARCHAR(256))
BEGIN

 SELECT dt1 as datep, var1 as vars, 'new' as type 
 FROM samp 
 UNION all
 SELECT v_dt2, v_col2, 'col2' as type 
 FROM samp 
 ;

END //
DELIMITER ;

CALL data1 ("dt2","var2","old")

在上面的括号中的调用语句是列名 但是在输出中将参数作为文本而不考虑作为列名...如何在UNION ALL之后的select语句中将它们转换为列名

1 个答案:

答案 0 :(得分:1)

您的过程返回常量值,而不是列名。要做你想做的事,你需要使用动态SQL(prepareexec):

CREATE PROCEDURE data1 (IN v_dt2 VARCHAR(256), v_col2 VARCHAR(256), col2 VARCHAR(256))
BEGIN
    set @s = '
SELECT dt1 as datep, var1 as vars, ''new'' as type 
FROM samp 
UNION all
SELECT @v_dt2, @v_col2, ''col2'' as type 
FROM samp ';

    set @s = replace(@s, '@v_dt2', v_dt2);
    set @s = replace(@s, '@v_col2', v_col2);
    set @s = replace(@s, '@col2', col2);

    prepare s from @s;
    exec s;

    deallocate prepare s;
END //
DELIMITER ;