title: mysql prepare: session variables vs parameters & local variables
body: <p>I'm using a stored procedure and prepare statements. I'd like to send in parameters to define which column to return from a select statement. This works if I use session variables and don't substitute variables. I can work around this, but I'd like to understand the issue. Here are examples:</p>
  
  <p>This works:</p>
  
  <pre><code>DELIMITER $$
  DROP PROCEDURE IF EXISTS `pnlByTheme` $$
  CREATE PROCEDURE `pnlByTheme`(IN param VARCHAR(50))
  BEGIN
    set @sqlStmt = concat("select ",param," from pnl_aggregate");
    prepare stmt from @sqlStmt;
    execute stmt;
  deallocate prepare stmt;
  END $$
  DELIMITER ;
  </code></pre>
  
  <p>When I call pnlByTheme('label'), I get the results of select label from pnl_aggregate, as I would from the command line. If I change the set statement to:</p>
  
  <pre><code>set @sqlStmt = "select ? from pnl_aggregate";
  </code></pre>
  
  <p>and then I change the execute statement to:</p>
  
  <pre><code>execute stmt using param;
  </code></pre>
  
  <p>mysql does not like that and won't create the procedure. if i instead change to:</p>
  
  <pre><code>DELIMITER $$
  
  DROP PROCEDURE IF EXISTS `pnlByTheme` $$
  CREATE PROCEDURE `pnlByTheme`(IN param VARCHAR(50))
  BEGIN
    set @p = param;
    set @sqlStmt = "select ? from pnl_aggregate";
    prepare stmt from @sqlStmt;
    execute stmt using @p;
  deallocate prepare stmt;
  END $$
  
  DELIMITER ;
  </code></pre>
  
  <p>that will create the procedure. why? what's strange (to me, anyway) is that the results of the call </p>
  
  <pre><code>call pnlbytheme('label');
  </code></pre>
  
  <p>are just literally "label" for each row rather than the actual data that I am looking for. I can easily work around this using concat, but want to understand. please help.</p>