简体   繁体   中英

MySQL Stored Procedure dynamic change name of table

I wanna change dynamicaly name of table in sql query. For example I have next stored procedure:

CREATE PROCEDURE NewProc(IN tableName varchar(64),IN message text)
BEGIN
    INSERT INTO tableName VALUES (message);
END;

I need to change tableName in runtime, Can I to do it or not? Thanks.

You must use dynamic SQL to prepare and execute an SQL string, to achieve what you describe.

Dynamic table names (or column names, or SQL keywords, etc.) must be interpolated into the SQL string before prepare. You can't use query parameters for these dynamic elements.

Be careful to avoid SQL injection vulnerabilities when you interpolate the table name into your SQL query. For example, you should check that the table name exists by looking it up in the information schema .

I agree with the comment from @OMG Ponies -- it's a code smell that you have multiple tables with identical structure such that you want to do the exact same insert to the exact same column. Code smells aren't a guarantee that you've got a bad design, but it's worth considering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM