Select column names whose entries are not null

前端 未结 2 494
心在旅途
心在旅途 2020-12-21 23:43

I would like to have a list of those columns of a table that have at least one non-NULL data entries in them.

In other words, I would like to get the co

相关标签:
2条回答
  • 2020-12-21 23:53

    Use this procedure this will print columns names of a table which have atleast one not null rows.

    create or replace procedure list_col_notNull(tblName in varchar2)
    as
    lv_col_name varchar2(200);
    lv_ctr number;
    lv_sql varchar2(400);
    CURSOR cur_col_name is
    SELECT column_name
    FROM USER_TAB_COLUMNS U
    WHERE table_name = tblName order by column_name asc;
    begin
    open cur_col_name;
    
    LOOP
        FETCH cur_col_name INTO lv_col_name; 
        EXIT WHEN cur_col_name%NOTFOUND; 
        lv_sql := 'select count(1) From ' || tblName || ' where ' || lv_col_name || ' is not null'  ;  
        EXECUTE IMMEDIATE lv_sql into lv_ctr;
        if lv_ctr > 0
        then
            dbms_output.put_line(lv_col_name);
        end if;
    
    0 讨论(0)
  • 2020-12-21 23:55

    Create from the INFORMATION_SCHEMA.COLUMNS table a string that contains the SQL you wish to execute, then prepare a statement from that string and execute it.

    The SQL we wish to build will look like:

      SELECT 'column_a'
      FROM   table_name
      WHERE `column_a` IS NOT NULL
      HAVING COUNT(*)
    UNION ALL
      SELECT 'column_b'
      FROM   table_name
      WHERE `column_b` IS NOT NULL
      HAVING COUNT(*)
    -- etc.
    

    (One could omit the WHERE clause and substitute COUNT(*) for COUNT(column), but I think that might be less efficient on indexed columns).

    This can be done using the following:

    SET group_concat_max_len = 4294967295;
    
    SELECT GROUP_CONCAT(
     ' SELECT ',QUOTE(COLUMN_NAME),
     ' FROM   table_name',
     ' WHERE `',REPLACE(COLUMN_NAME, '`', '``'),'` IS NOT NULL',
     ' HAVING COUNT(*)'
    SEPARATOR ' UNION ALL ')
    INTO   @sql
    FROM   INFORMATION_SCHEMA.COLUMNS
    WHERE  TABLE_SCHEMA = DATABASE()
       AND TABLE_NAME = 'table_name';
    
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    

    See it on sqlfiddle.

    0 讨论(0)
提交回复
热议问题