Skip to content

2253. Dynamic Unpivoting of a Table

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
CREATE PROCEDURE UnpivotProducts()
BEGIN
  # Override GROUP_CONCAT length which has a default limit of 1024.
  SET SESSION group_concat_max_len = 1000000;

  SELECT GROUP_CONCAT(
      CONCAT(
        'SELECT product_id, "',
        `column_name`, '" AS store, ',
        `column_name`, ' AS price ',
        'FROM products ',
        'WHERE ',
        `column_name`, ' IS NOT NULL'
      ) SEPARATOR ' UNION '
    ) INTO @stmt
  FROM `information_schema`.`columns`
  WHERE
    `table_schema` = 'test'
    AND `table_name` = 'Products'
    AND `column_name` != 'product_id';

  PREPARE final_query FROM @stmt;
  EXECUTE final_query;
  DEALLOCATE PREPARE final_query;
END