• The Four Hundred
  • Subscribe
  • Media Kit
  • Contributors
  • About Us
  • Contact
Menu
  • The Four Hundred
  • Subscribe
  • Media Kit
  • Contributors
  • About Us
  • Contact
  • Generate SELECT For All Columns

    September 13, 2016 Hey, Mike

    I have a table with a long list of column names and I want to build a SELECT statement from the catalog metadata. If I supply schema (library) and table (physical file) names, is there a way to generate a SELECT statement?

    —Four Hundred Guru Reader

    Thanks to dynamic compound statements and global variables, the answer is yes, it’s fairly easy to construct a SQL statement for a table or view as shown below:

    /* Build Select Statement and stuff it in QGPL.TEMPSQL variable */
    BEGIN
        -- Fill in your table/schema name
        DECLARE @TABLE_NAME   VARCHAR(128) NOT NULL 
                              DEFAULT 'SYSCOLUMNS';
        DECLARE @TABLE_SCHEMA VARCHAR(128) NOT NULL 
                              DEFAULT 'QSYS2';
        DECLARE @SQL          VARCHAR(24576) NOT NULL 
                              DEFAULT '';
    
        -- Create QGPL.TEMPSQL variable if it doesn't exist
        IF NOT EXISTS (
        SELECT *
          FROM QSYS2.SYSVARIABLES
         WHERE VARIABLE_SCHEMA='QGPL' 
           AND VARIABLE_NAME='TEMPSQL') THEN
            EXECUTE IMMEDIATE 'CREATE VARIABLE QGPL.TEMPSQL VARCHAR(24576)';
        END IF;
    
        -- Build comma delimited column name list
        FOR TEMP AS COLUMNS CURSOR FOR
        SELECT COLUMN_NAME
          FROM QSYS2.SYSCOLUMNS
         WHERE TABLE_SCHEMA=@TABLE_SCHEMA
           AND TABLE_NAME=@TABLE_NAME
        DO
            SET @SQL = @SQL
                       || CASE WHEN LENGTH(@SQL)>0 THEN ',' ELSE '' END
                       || COLUMN_NAME;
        END FOR;
    
        -- Build SQL statement
        SET @SQL='SELECT '||@SQL||
                  ' FROM '||@TABLE_SCHEMA||'.'||@TABLE_NAME;
    
        -- Save SQL statement in variable
        SET QGPL.TEMPSQL=@SQL;
    END
    ;
    -- Display the SQL statement
    VALUES(QGPL.TEMPSQL);
    

    The result is:

    SELECT COLUMN_NAME,TABLE_NAME,TABLE_OWNER,ORDINAL_POSITION,DATA_TYPE,LENGTH,NUMERIC_
    SCALE,IS_NULLABLE,IS_UPDATABLE,LONG_COMMENT,HAS_DEFAULT,COLUMN_HEADING,STORAGE,
    NUMERIC_PRECISION,CCSID,TABLE_SCHEMA,COLUMN_DEFAULT,CHARACTER_MAXIMUM_LENGTH,
    CHARACTER_OCTET_LENGTH,NUMERIC_PRECISION_RADIX,DATETIME_PRECISION,COLUMN_TEXT,
    SYSTEM_COLUMN_NAME,SYSTEM_TABLE_NAME,SYSTEM_TABLE_SCHEMA,USER_DEFINED_TYPE_SCHEMA,
    USER_DEFINED_TYPE_NAME,IS_IDENTITY,IDENTITY_GENERATION,IDENTITY_START,
    IDENTITY_INCREMENT,IDENTITY_MINIMUM,IDENTITY_MAXIMUM,IDENTITY_CYCLE,IDENTITY_
    CACHE,IDENTITY_ORDER,COLUMN_EXPRESSION,HIDDEN,HAS_FLDPROC FROM QSYS2.SYSCOLUMNS
    

    This isn’t the prettiest to look at but it beats typing everything by hand. It’s easy to modify the code to insert a carriage return/line feed after each column name if, for example, each column is preferred on its own line. It’s also easy to modify the code to ignore columns with certain data types, unwanted column names, etc.

    This same principle can be applied to automatically build the base of INSERT/VALUES and UPDATE statements. For an advanced treatment of a similar topic involving the generation of INSERT statements with data, see Paul Touhy’s tip Generating An Insert Script From Existing Data.

    This script should be run in a graphical SQL tool like iNavigator’s RunSQL scripts. The above statements can be run in STRSQL but you first have to remove the double-hyphenated comments and remove the semicolons after the dynamic compound statement and after the VALUES statement.

    –Mike Sansoterra

    Michael Sansoterra is a DBA for Broadway Systems in Grand Rapids, Michigan. Send your questions or comments for Mike via the IT Jungle Contact page.

    RELATED STORY

    Generating An Insert Script From Existing Data

    Share this:

    • Reddit
    • Facebook
    • LinkedIn
    • Twitter
    • Email

    Tags:

    Sponsored by
    DRV Tech

    Get More Out of Your IBM i

    With soaring costs, operational data is more critical than ever. IBM shops need faster, easier ways to distribute IBM applications-based data to users more efficiently, no matter where they are.

    The Problem:

    For Users, IBM Data Can Be Difficult to Get To

    IBM Applications generate reports as spooled files, originally designed to be printed. Often those reports are packed together with so much data it makes them difficult to read. Add to that hardcopy is a pain to distribute. User-friendly formats like Excel and PDF are better, offering sorting, searching, and easy portability but getting IBM reports into these formats can be tricky without the right tools.

    The Solution:

    IBM i Reports can easily be converted to easy to read and share formats like Excel and PDF and Delivered by Email

    Converting IBM i, iSeries, and AS400 reports into Excel and PDF is now a lot easier with SpoolFlex software by DRV Tech.  If you or your users are still doing this manually, think how much time is wasted dragging and reformatting to make a report readable. How much time would be saved if they were automatically formatted correctly and delivered to one or multiple recipients.

    SpoolFlex converts spooled files to Excel and PDF, automatically emailing them, and saving copies to network shared folders. SpoolFlex converts complex reports to Excel, removing unwanted headers, splitting large reports out for individual recipients, and delivering to users whether they are at the office or working from home.

    Watch our 2-minute video and see DRV’s powerful SpoolFlex software can solve your file conversion challenges.

    Watch Video

    DRV Tech

    www.drvtech.com

    866.378.3366

    Share this:

    • Reddit
    • Facebook
    • LinkedIn
    • Twitter
    • Email

    Sponsored Links

    System i Developer:  RPG & DB2 Summit - October 4-6 2016 in Chicago. Register now!
    BCD:  Webinar: What's Possible with PHP on IBM i. Tues., Sept. 27 at 1pm ET. Sign up now!
    Manta Technologies Inc.:  The Leader in IBM i Education! Download catalog and take sample sessions!

    Howdy, Partner. Welcome To The IBM i Modernization Ranch New OpenPower Servers Present Interesting IBM i Possibilities

    One thought on “Generate SELECT For All Columns”

    • Carlos Torres says:
      May 25, 2021 at 2:57 pm

      Hi Michael,
      I was able to build the SQL string using the SQL compound statement like the one in your blog GENERATE SELECT FOR ALL COLUMNS and save it in a SQL variable. Now I’m running into a concern as how can I run the SQL statement from the SQL variable? or is there any chance I can run it from the SQL compound statement itself using something like EXEC …before I END the compound statement?
      Much appreciate your feedback.

      Reply

    Leave a Reply Cancel reply

Volume 16, Number 20 -- September 13, 2016
THIS ISSUE SPONSORED BY:

WorksRight Software
ProData Computer Services
UCG Technologies

Table of Contents

  • How Do You Do That With RDi? Part 1: Copy A Source Member
  • Determine The State Of The Error
  • Generate SELECT For All Columns

Content archive

  • The Four Hundred
  • Four Hundred Stuff
  • Four Hundred Guru

Recent Posts

  • The Power11 Transistor Count Discrepancies Explained – Sort Of
  • Is Your IBM i HA/DR Actually Tested – Or Just Installed?
  • Big Blue Delivers IBM i Customer Requests In ACS Update
  • New DbToo SDK Hooks RPG And Db2 For i To External Services
  • IBM i PTF Guide, Volume 27, Number 33
  • Tool Aims To Streamline Git Integration For Old School IBM i Devs
  • IBM To Add Full System Replication And FlashCopy To PowerHA
  • Guru: Decoding Base64 ASCII
  • The Price Tweaking Continues For Power Systems
  • IBM i PTF Guide, Volume 27, Numbers 31 And 32

Subscribe

To get news from IT Jungle sent to your inbox every week, subscribe to our newsletter.

Pages

  • About Us
  • Contact
  • Contributors
  • Four Hundred Monitor
  • IBM i PTF Guide
  • Media Kit
  • Subscribe

Search

Copyright © 2025 IT Jungle