MySQL在select语句中生成带循环的列

时间:2012-01-14 10:51:50

标签: mysql function select loops

在MySQL中,我有一个函数,它接受一个数字参数,并根据该数字从另一个表中吐出一部分结果。目前的实施情况如下:

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

你可以在select语句中使用循环(甚至是构建表的过程),所以上面变成:

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

感谢。

1 个答案:

答案 0 :(得分:3)

是的,你可以......看看DynamicSQL ..

Here's one sample

and another example

通常,您构建一个包含要执行的SQL语句的字符串,然后准备它,然后执行它......