Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

sql - How to write a mysql function with dynamic table name?

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

1064 - You have an error in your SQL syntax; check the manual that corresponds to 
  your MySQL server version for the right syntax to use near 'table DETERMINISTIC 
  BEGIN select `r`.`id` AS `id`, (case ' at line 2

This is my query

DELIMITER $$
CREATE FUNCTION getTranslation (tablename varchar(50),entity varchar(20),itemid int,lang char(3)) 
RETURNS table
DETERMINISTIC
BEGIN 
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`)))
END$$
DELIMITER ;

I the select part works fine with static table name by the way.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...