如何创建将接受参数的存储过程

时间:2011-03-02 19:43:25

标签: mysql sql stored-procedures

我有一套“SQL语句”

DROP TABLE IF EXISTS data.s;
CREATE TABLE data.s LIKE data._style;
INSERT INTO data.s Values (?,?,?,?,?,?,?,?,?,?,?,?,?);

UPDATE data.s n JOIN data.s_ o ON n.ID = o.ID SET n.TC = o.TC;
UPDATE data.s n JOIN data.s_ o ON n.ID = o.ID SET n.VR = o.VR;
UPDATE data.s n JOIN data.o_ o ON n.ID = o.ID SET n.OC = o.OC;
DELETE FROM data.s WHERE TC <= 0;
DELETE FROM data.s WHERE TC < 100;
DELETE FROM data.s WHERE OC < 100 ;

以“s”表为例,我如何创建一个SP,其中“s”是一个变量,可以替换为t,u v,z ......无论如何?我想用SQL调用语句来改变这个变量。

1 个答案:

答案 0 :(得分:2)

MySQL不处理真正的动态SQL,所以你必须使用预准备语句。

查看已接受的答案:How To have Dynamic SQL in MySQL Stored Procedure,尤其是他提供的链接(动态SQL部分)。

类似的东西:

CREATE PROCEDURE `execute`(IN sqlQuery varchar(255))
BEGIN

    set @sqlQuery := sqlQuery;

    prepare stmp from @sqlQuery; 

    execute stmp;

    deallocate prepare stmp; 

END

CREATE PROCEDURE `yourProcName`(IN tableName varchar(50))
BEGIN

    call execute(concat('DROP TABLE IF EXISTS ', tableName));
    call execute(concat('CREATE TABLE ', tableName, ' LIKE data._style'));

    ...

END