Search code examples
hana

How to select columns which are not null in SAP HANA?


So I have a base table - TRAINING, which has 100 columns. Some of the columns will be completely NULL and some will contain Values. So say COLUMN 1-20 are null and COLUMN 21-100 are not NULL.

I have another table called - CONFIGURATION. It has only one column of type VARCHAR. This table contains the name of those columns from the TRAINING table that are not NULL. So it'll contain values - COLUMN 21-100.

What I want to do is- fetch the data of only those columns that are not NULL. So I want the output as the data points contained in table COLUMN 21-100. This number may be different every time and it can also be interleaved, say COLUMN 1-10 is NULL and COLUMN 11-25 not NULL and the remaining again NULL.

I am thinking of implementing inner Join but I do not have the table structure required for it.

Please provide some hint.

Thanks.


Solution

  • You need to create dynamic SQL for that.

    First step - create ALL_COLUMNS variable of VARCHAR(5000) data type. From your CONFIGURATION table select column names which you want to query. Then use STRING_AGG function to aggregate them into single value (in my example COL1 is column from CONFIGURATION table). Assign output to the ALL_COLUMNS variable

    Second step use EXECUTE IMMEDIATE to run dynamic SQL. Add ALL_COLUMNS variable as input for that query.

    Here is the examplary code:

    DO
    BEGIN
    
    /* First Step - create string with all column names separated by comma*/
    
        DECLARE ALL_COLUMNS VARCHAR(5000);
    
        SELECT  STRING_AGG(COL1,',' ORDER BY COL1)  INTO ALL_COLUMNS FROM CONFIGURATION;
    
    /*Second Step - create dynamic SQL including variable from First Step*/
    
        EXECUTE IMMEDIATE ('SELECT ' || :ALL_COLUMNS  || ' FROM "TRAINING" ');
    
    END