mysql,遍历列名

时间:2011-02-09 20:45:45

标签: sql 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的复杂性,这真的有助于我的项目。谢谢你的帮助。

2 个答案:

答案 0 :(得分:18)

我想你想要这样的东西:

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;

答案 1 :(得分:4)

您可以针对information_schema编写查询以获取列名称:

SELECT column_name
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE table_name = 'tbl_name'
  ORDER BY ordinal_position

然后返回列名,就像表中的任何数据一样。