0

tbl1 からすべての列を選択したいのですが、MySQL ストア プロシージャに空のデータがある列は選択したくありません。

次のような私の構造:

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

select * from tbl1 where .....

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

1 に答える 1

0

Here is how you can do it. Assumption is that by ...column that has empty data... you mean a column with NULL values for all rows.

DELIMITER $$
CREATE PROCEDURE 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) INTO @cols FROM (', 
                 @sql, 
                 ') q WHERE q.n > 0'
               );
    PREPARE stmt FROM @sql;
    EXECUTE stmt;

    SET @sql = CONCAT('SELECT ', @cols, ' FROM ', @tbl);
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    END$$
DELIMITER ;

Then you call the procedure

CALL sp_select();

And you'll get

+------+------+------+
| Name | val1 | val3 |
+------+------+------+
| a    |    1 |    2 |
| b    |    4 |    4 |
| c    |    5 |    7 |
| e    |    7 |    6 |
+------+------+------+

Here is SQLFiddle demo.

于 2013-06-22T11:26:00.120 に答える