Oracle: Finding Columns with only null values

前端 未结 8 2077
温柔的废话
温柔的废话 2021-01-17 21:11

I have a table with a lot of columns and a type column.

Some columns seem to be always empty for a specific type.

I want to create a view for each type and o

8条回答
  •  不知归路
    2021-01-17 21:51

    I think you can solve this using metaprogramming. Use a cursor to loop through each type and column, and use 'not exists' to check if the column is empty. For example:

    CREATE TABLE result_table (type VARCHAR(50), column VARCHAR(50))
    
    CURSOR c IS
        SELECT COLUMN_NAME FROM ALL_TAB_COLS WHERE TABLE_NAME = &table_name;
    
    CURSOR ct IS
        SELECT DISTINCT type_name FROM &table_name;
    
    BEGIN
    
    FOR t in ct
    LOOP
        FOR r in c
        LOOP
            --If you're confused about how this works, replace 'EXECUTE IMMEDIATE'
            --with print or something and look at the output
            EXECUTE IMMEDIATE
                'INSERT INTO result_table SELECT ''' ||
                    t.type_name || ''', ''' || r.COLUMN_NAME ||
                    ''' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM ' || 
                    &table_name || ' WHERE t.type_name = ''' || t.type_name ||
                    ''' AND ' || r.COLUMN_NAME || ' IS NOT NULL);';
        END LOOP
    END LOOP
    
    SELECT * FROM result_table
    

    Apologies if there's a mistake in the syntax somewhere, I have nothing to check this on.

提交回复
热议问题