Get table column Name using cursor | Mysql Get table column using procedure.

Try this procedure to return the column values from the table.
CREATE PROCEDURE GET_TABLE_COLUMNNAME_LIST(tableName VARCHAR(30), OUT columnNameList VARCHAR(300))
BEGIN
   DECLARE columnName VARCHAR(30);
   DECLARE firstEntry INT DEFAULT 0;
   DECLARE NOT_FOUND INT DEFAULT 0;
 
   DECLARE table_column_names_cursor CURSOR FOR
   
     SELECT DISTINCT(column_name) FROM INFORMATION_SCHEMA.COLUMNS WHERE LOWER(table_name) = LOWER(tableName);
   DECLARE CONTINUE HANDLER FOR NOT FOUND SET NOT_FOUND = 1;
 
   OPEN table_column_names_cursor;
   FETCH table_column_names_cursor INTO columnName;
   REPEAT
 
     IF (firstEntry != 0) THEN
       SET columnNameList = CONCAT(columnNameList, ',', columnName);
     ELSE
       SET columnNameList = columnName;
       SET firstEntry = firstEntry + 1;
     END IF;
     FETCH table_column_names_cursor INTO columnName;
   UNTIL NOT_FOUND END REPEAT;
 
   CLOSE table_column_names_cursor;
 END
Execute store procdure.
call GET_TABLE_COLUMNNAME_LIST('citymas',@columnNameList);
SELECT @columnNameList;
Result:

Or 
SELECT group_concat('`',column_name,'`') FROM  information_schema.COLUMNS  where table_schema=@DB and table_name=@Table;

Post a Comment

0 Comments