Bug #31216 Cannot use dynamic table name in SHOW COLUMNS inside a stored function
Submitted: 26 Sep 2007 21:00 Modified: 27 Sep 2007 11:13
Reporter: Ryan T Email Updates:
Status: Not a Bug Impact on me:
None 
Category:MySQL Server: Stored Routines Severity:S3 (Non-critical)
Version:5.0.15-nt OS:Any
Assigned to: CPU Architecture:Any
Tags: PROCEDURE, show

[26 Sep 2007 21:00] Ryan T
Description:
When creating a cursor that runs the SHOW COLUMNS query inside a stored function the name of the table cannot be set with a variable.. so it seems.

Why am i trying to do this in a function?  I'm trying to concat the names of the columns from a specific list of tables.  However, since the DECLARE CURSOR sql statement is not updatable and must be declared at the beginning of the function block i need two functions to do this.  It would work if only the SHOW COLUMNS statement would accept a variable for the table name inside the function.

If there is another way to obtain a list of columns in a table (without using the slow information schema) inside a function please describe how.

Thanks!

How to repeat:
DELIMITER $$

DROP FUNCTION IF EXISTS `bc_admin`.`GetCols` $$
CREATE FUNCTION `bc_admin`.`GetCols`(tab_name varchar(100)) RETURNS text CHARSET latin1
BEGIN
  DECLARE ret text;
  DECLARE done int;
  DECLARE col_name,f2,f3,f4,f5,f6 varchar(200);
  DECLARE cols CURSOR FOR SHOW COLUMNS IN tab_name;
  DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;

  SET done=0;
  SET ret='';
  OPEN cols;
  col_data:LOOP
    FETCH cols INTO col_name,f2,f3,f4,f5,f6;
    IF (done=1) THEN LEAVE col_data; END IF;
    SET ret = CONCAT(ret,'-',col_name);
  END LOOP;
  RETURN ret;
END $$

DELIMITER ;

Now run:
SELECT GetCols('mytable');

Which returns:
Table 'bc_admin.tab_name' doesn't exist

It should return:
Table 'bc_admin.mytable' doesn't exist
OR the concat list of column names if the table does exist

Suggested fix:
Other sql statements replace local variable names with their proper value, so why not the tab_name variable in the SHOW COLUMNS query?

If the query "SHOW COLUMNS IN tab_name" was changed to "SELECT tab_name" then the output shows that the variable value is used, which is what i would expect.
[27 Sep 2007 11:13] Sveta Smirnova
Thank you for taking the time to write to us, but this is not a bug. Please double-check the documentation available at http://dev.mysql.com/doc/ and the instructions on
how to report a bug at http://bugs.mysql.com/how-to-report.php

According to http://dev.mysql.com/doc/refman/5.1/en/user-variables.html:

User variables may be used in contexts where expressions are allowed.

You hitted this case.