MySQL producing columns with loop in a select statement

28,563

yes you can... take a look into DynamicSQL..

Here's one sample

and another example

In general, you build a string that contains the SQL statement you want to execute, then prepare it, then execute it...

Share:
28,563
Trees4theForest
Author by

Trees4theForest

Updated on July 09, 2022

Comments

  • Trees4theForest
    Trees4theForest almost 2 years

    In MySQL I have a function that takes a number argument and spits out a subset of results from another table, based on that number. Implementation currently looks like:

    SELECT 
      id,
      date,
      function(do stuff with value 1) as t1,
      function(do stuff with value 2) as t2,
      function(do stuff with value 3) as t3,
      ...
      function(do stuff with value N) as tN
    FROM table
    

    Can you use a loop in a select statement (or even a procedure that builds a table) so the above becomes:

    SELECT
      id,
      date,
      LOOP x = 1 through N
        function(do stuff with value x) as tx,
      END LOOP
    FROM table
    

    Thanks.