Tuesday 15 September 2015

stored procedures - mysql get column but not include empty column -


I would like to select all the columns from tbl1 but not in the column which is empty data in the MySQL store process.

My structure is as follows:

  tbl1 name val1 val2 val3 val4 a 1 2 b 4 4 c 5 7 e 7 6   

Choose * from Tbl1 where .....

  Results: Name val1 val3 a 1 2 b 4 4 c 5 7 e 7 6    

Here's how you can do this: ... column has empty data ... means the column with value NULL for all the rows

  DELIMITER $$ creation process sp_select () BEGIN SET @tbl = 'tbl1', @sql = NULL, @cols = NULL; SELECT GROUP_CONCAT (CONCAT ('SELECT'), 'column_name`,' '' name, COUNT (',' column_name`, ') n FROM', @tbl) SEPARATOR 'union all') INTO @ sql from INFORMATION_SCHEMA.COLUMNS WHERE Table_name = @tbl; SET @sql = CONCAT (Select 'GROUP_CONCAT (name)' @ cols FROM (', @sql,' q where q.n & gt; 0 '); Prepare SSML with SSMT; EXTUTE STMT; SET @sql = CONCAT ('SELECT', @cols, 'FROM', @tbl); Prepare SSML with SSMT; EXTUTE STMT; DEALLOCATE STMT; END $$ DELIMITER;   

Then you call the process

  call sp_select ();   

and you will get

 + ------ + ------ + ------ + | Name | Val1 | Val3 | + ------ + ------ + ------ + | One | 1 | 2 | | B 4 | 4 | | C. 5 | 7 | | E 7 | 6 | + ------ + ------ + ------ +  

Here is the demo.

No comments:

Post a Comment