Search code examples
mysqlsqlstored-proceduresmysql-variables

Using the input parameters from stored parameters as variables inside where clause MySQL


I have a simple mysql table:

CREATE TABLE  `cont` (
  `ID` int(11) NOT NULL,
  `Meeting_id` int(11) DEFAULT NULL,
  `member_name` varchar(20) NOT NULL,
  `cont_prod` varchar(20) NOT NULL,
  `start_date` date NOT NULL,
  `type_of` varchar(100),
  `ord_qty` int(11) DEFAULT NULL
) ;

I am trying to dynamically transpose rows to columns following this example enter link description here

  1. In side the SELECT STATEMENT when I use the input parameters inside WHERE clause it is giving me error column not found.

  2. I tried to declare the variable as :

    SET @v1 = c_prod; SET @v2 = s_date;

and teh in the where clause:

WHERE cont_prod = @v1 AND start_date = @v2

it is still not working

How can I define the input parameter variable inside the WHERE clause?

Any help would be highly apprecuited.

 BEGIN
         SET @sql = NULL;
    SELECT
      GROUP_CONCAT(DISTINCT
        CONCAT(
          'max(case when type_of = '',
          type_of,
          '' then ord_qty end) ',
          type_of
        )
      ) INTO @sql
    FROM
      cont
      where cont_prod = c_prod AND start_date = s_date;
    SET @sql = CONCAT('SELECT product_id,member_name,start_date,cont_prod, ', @sql, ' 
                      FROM cont WHERE cont_prod = c_prod AND start_date = s_date
                       GROUP BY member_name,cont_prod,start_date');
    
    PREPARE stmt FROM @sql;
    EXECUTE st......

Solution

  • Use ? to specify parameters in the prepared statement, and pass the parameters on the EXECUTE line.

    SET @sql = CONCAT('SELECT product_id,member_name,start_date,cont_prod, ', @sql, ' 
                FROM cont WHERE cont_prod = ? AND start_date = ?
                GROUP BY member_name,cont_prod,start_date');
    PREPARE stmt FROM @sql;
    EXECUTE stmt USING c_prod, s_date;