Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL producing columns with loop in a select statement

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.

like image 532
Trees4theForest Avatar asked Oct 18 '25 07:10

Trees4theForest


1 Answers

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...

like image 155
DRapp Avatar answered Oct 19 '25 23:10

DRapp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!