一尘不染

mysql,遍历列名

mysql

我想从MySQL表中获取所有列名,遍历每个列名,然后使用这些列名作为变量运行存储过程。效果:

colnames = get column names from table

for each colname
  if something changed then
    do something
  else
    do something else

看起来SHOW COLUMNS FROM myTable会给我列名,但是如何将列名放入循环?

我真的很想使用本机SQL在存储过程中运行所有这些程序。由于我仍在学习MySQL的复杂性,因此对我的项目确实有帮助。谢谢你的帮助。


阅读 406

收藏
2020-05-17

共1个答案

一尘不染

我想你想要这样的东西:

DECLARE col_names CURSOR FOR
  SELECT column_name
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE table_name = 'tbl_name'
  ORDER BY ordinal_position;


select FOUND_ROWS() into num_rows;

SET i = 1;
the_loop: LOOP

   IF i > num_rows THEN
        CLOSE col_names;
        LEAVE the_loop;
    END IF;


    FETCH col_names 
    INTO col_name;

     //do whatever else you need to do with the col name

    SET i = i + 1;  
END LOOP the_loop;
2020-05-17