Search code examples
sqldb2-400

DB2 Select column names from nested select


I was trying to select columns from sys columns lib, but function LISTAGG returns only a varchar which then gets listed instead of listing columns returned by nested select

  SELECT (SELECT LISTAGG(COLUMN_NAME, ',')
            FROM QSYS2.SYSCOLUMNS
            WHERE TABLE_NAME = 'MYTABLE' AND COLUMN_TEXT LIKE '%Date%'
            GROUP BY TABLE_NAME
            FETCH FIRST 1 ROW ONLY)
    FROM subsystem.MYTABLE

is there a way to cast this subselect result to type which can be then selected? or some other way to reach same result


Solution

  • This can be done, but not in a single statement like you are trying to do.

    You'll need two statements with one of them being an "dynamic" statement that gets prepared. Normally, it'd be PREPARE and EXECUTE but since you want to return the data, you'll also need a cursor.

    The statements will also need to be imbedded into a application program, SQL stored procedure or function.

    create or replace procedure mylib.rtnDates()
    result sets 1
    language sql
    begin
        declare myColList varchar(1000);
        declare mySqlStmtText varchar(3000);
        declare returnDates cursor with return to client for mySqlStmt;
        
        -- note neither group by nor FETCH FIRST 1 ROW is needed
        -- if you limit the select to a single table in a single schema
        -- which is probably what you need
        SELECT  LISTAGG(COLUMN_NAME, ',') into myColList
          FROM QSYS2.SYSCOLUMNS
          WHERE TABLE_NAME = 'MYTABLE' AND COLUMN_TEXT LIKE '%Date%'
                and table_schema = 'MYLIB';
        
        set mySqlStmtText = 'select ' concat myColList concat ' from mylib.mytable';
        
        prepare mySqlStmt from mySqlStmtText;
        open  returnDates;
    end;
    
    call mylib.rtnDates();