MySQL table names into stored procedures and functions


2011-01-17 Digg! icurtain Delcious icurtain

As an aid memoir; Firstly, to create stored procedures in MySQL you need to temporarily change the line delimiter so you can add code with normal delimiters without delimiting what you're currently doing. 

Secondly, in order to use variables passed into a procedure you need to concatenate into a statement, you can't just "select * from myPassedVariableName".  

The example below will count() the id column of any given table 

 
  1.       DELIMITER $$ 
  2.  
  3.       DROP PROCEDURE IF EXISTS `countIds`$$ 
  4.       CREATE PROCEDURE   `countIds`(IN tbl CHAR(64))
  5.  
  6.       BEGIN 
  7.          SET @s = CONCAT('SELECT count(id) AS cnt FROM ' , tbl); 
  8.  
  9.          PREPARE stmt FROM @s; 
  10.          EXECUTE stmt; 
  11.       END $$ 
  12.  
  13.       DELIMITER ;