How to write a mysql function with dynamic table name?

后端 未结 2 1351
太阳男子
太阳男子 2020-12-22 03:03

I\'m trying to write a my sql function doing the following things: 1- get the table name used in join as a parameter.

but I get mysql syntax error

10         


        
相关标签:
2条回答
  • 2020-12-22 03:26

    Give this a try

    SET @ex = CONCAT('select `r`.`id` AS `id`,(case when isnull(`t`.`descr`) then `r`.`descr_ml` else `t`.`descr` end) AS `descr` from (',tablename,' `r` left join `g001_translation` `t` ON ((`t`.`item_id` = `r`.`id`)));');
        PREPARE stmt FROM @ex;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    

    You will notice that ',tablename,' will use the parameter passed.

    0 讨论(0)
  • 2020-12-22 03:32

    First up as mentioned by @eggyal this isn't the best way to go about things. But it can be done by using prepared statements. I.e.

    DROP PROCEDURE IF EXISTS `exampleOfPrepareStatement`;
    
    CREATE DEFINER = `user`@`%` PROCEDURE `exampleOfPrepareStatement`(inTableName VARCHAR(100))
        MODIFIES SQL DATA
        SQL SECURITY INVOKER
    BEGIN
    
        SET @hr1 = CONCAT('
            INSERT INTO `',inTableName,'` (
                -- fields (can use parameters same as table name if needed)
            )
            -- either VALUES () or SELECT here
        ');
    
        -- Prepare, execute, deallocate
        PREPARE hrStmt1 FROM @hr1;
        EXECUTE hrStmt1;
        DEALLOCATE PREPARE hrStmt1;
    
    END;
    

    You can of course add in field names etc. as needed, or use a SELECT or UPDATE etc. This is not ideal, but will do what you are looking for.

    I have had to use this in some places before where the same maintenance is being performed on multiple tables which have different field names ( / table names ) and so instead of writing the same function 20 times, instead I use this type of stored procedure which can then be called to do the indexing etc.

    As also mentioned by @eggyal , while this may do as you ask, it might not do as you need. If you can provide more information then you may get a better solution.

    0 讨论(0)
提交回复
热议问题