• 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
    Midrange Dynamics North America

    Git up to speed with MDChange!

    Git can be lightning-fast when dealing with just a few hundred items in a repository. But when dealing with tens of thousands of items, transaction wait times can take minutes.

    MDChange offers an elegant solution that enables you to work efficiently any size Git repository while making your Git experience seamless and highly responsive.

    Learn more.

    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

  • Public Preview For Watson Code Assistant for i Available Soon
  • COMMON Youth Movement Continues at POWERUp 2025
  • IBM Preserves Memory Investments Across Power10 And Power11
  • Eradani Uses AI For New EDI And API Service
  • Picking Apart IBM’s $150 Billion In US Manufacturing And R&D
  • FAX/400 And CICS For i Are Dead. What Will IBM Kill Next?
  • Fresche Overhauls X-Analysis With Web UI, AI Smarts
  • Is It Time To Add The Rust Programming Language To IBM i?
  • Is IBM Going To Raise Prices On Power10 Expert Care?
  • IBM i PTF Guide, Volume 27, Number 20

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