Mysql stored procedure don't take table name as parameter

后端 未结 4 1754
不思量自难忘°
不思量自难忘° 2020-12-03 16:47

I\'ve written a stored procedure. It\'s working fine except taking the table name as input parameter.

Let see my proc in MySQL:

DELIMITER $$
USE `d         


        
相关标签:
4条回答
  • An SP cannot be optimized with a dynamic table name, so many DBs, MySQL included, don't allow table names to be specified dynamically.

    One way around this is to use Dynamic SQL.

    CREATE DEFINER=`root`@`localhost` PROCEDURE `test_proc`(IN serviceName VARCHAR(10),IN newsInfoTable VARCHAR(100))
    BEGIN                  
        SET @sql = CONCAT('SELECT COUNT(*) FROM ',newsInfoTable,' WHERE newsServiceName=?;'); 
        PREPARE s1 from @sql;
        SET @paramA = serviceName;
        EXECUTE s1 USING @paramA;
    END$$
    
    0 讨论(0)
  • 2020-12-03 16:56

    You can use EXECUTE IMMEDIATE for a "less is more" solution (for me, less code = good)

    CREATE PROCEDURE test_proc(IN serviceName VARCHAR(10), IN newsInfoTable VARCHAR(100))
    BEGIN                  
        EXECUTE IMMEDIATE CONCAT('SELECT COUNT(*) FROM ',newsInfoTable,' WHERE newsServiceName=''', serviceName, ''''); 
    END
    
    0 讨论(0)
  • 2020-12-03 16:56

    that part of a query cannot be dynamic.

    you may consider implementing as a string that is executed dynamically at runtime

    0 讨论(0)
  • 2020-12-03 17:03

    Although may not be what you want, alternatively, can consider to use conditionally if and prepare the statement.

    DELIMITER $$
    CREATE PROCEDURE select_count(IN table_name VARCHAR(20))
    BEGIN
      IF table_name = 'xxx' THEN
         SELECT * FROM xxx;
      ELSEIF table_name = 'yyy' THEN
         ...
      ENDIF
    END$$
    
    0 讨论(0)
提交回复
热议问题