• The Four Hundred
  • Subscribe
  • Media Kit
  • Contributors
  • About Us
  • Contact
Menu
  • The Four Hundred
  • Subscribe
  • Media Kit
  • Contributors
  • About Us
  • Contact
  • Accessing Multiple DB2 Relational Databases In A Single Query

    August 8, 2012 Michael Sansoterra

    In my prior tip, I covered a new feature provided in the i7.1 technology refresh 4 update that allows a INSERT/SELECT statement to insert data into a local DB2 for i table from a query against a remote DB2 database. In this tip, I will cover a method that can be used to query multiple DB2 relational databases in a single statement.

    Author’s Note: Incidentally, the remote DB2 database can be another member of the DB2 family besides DB2 for i. Check out my article on DB2 for Windows for more information.

    As I mentioned in my last tip, with DB2 for i7.1, remote database access can be accomplished without using a CONNECT statement. Also, each SQL query against a remote database can access only one remote relational database at a time that can create a problem if you need to simultaneously access multiple remote databases with a single query.

    The way to “weasel” around this restriction is to understand that user-defined table functions (UDTF) are an island unto themselves. A UDTF can be coded to access a single remote database. However, multiple UDTFs (each potentially accessing a different remote database) can be combined in a single query. In the end, several UDTFs (each accessing a single remote database) can be combined in a single SELECT statement that effectively accesses multiple remote databases at once.

    Before we begin, this technique uses DRDA to connect the local and remote IBM i machines (or partitions.)

    The Demonstration

    For a simple demo, say we have three IBM i partitions: a local system, SYSTEMA, and SYSTEMB. Each partition has one or more tables that we want to combine in a single query as shown in Table 1 below:




    System (Remote Relational Database)

    System (Remote Relational Database)

    Tables

    Local

    SalesOrderHeader,SalesOrderDetail

    SystemA

    Product

    SystemB

    Customer,Store,Contct

    Table 1: Distribution of tables in sample heterogeneous query.

    In case you couldn’t tell, I took sample tables from the AdventureWorks 2005 sample database and spread them out onto three partitions for this example.

    To bring the Product data from SystemA to our local partition, we can create a UDTF on the local partition that references the Product table on the remote SystemA using the three-part naming convention:

    CREATE OR REPLACE FUNCTION DEV.RMTPRODUCT()
    RETURNS TABLE
    (PRODUCTID INT, 
     NAME NVARCHAR(50), 
     PRODUCTNUMBER NVARCHAR(25), 
     SAFETYSTOCKLEVEL INT) 
    LANGUAGE SQL
    DISALLOW PARALLEL
    CARDINALITY 150
    SET OPTION COMMIT=*NONE
    RETURN
        SELECT PRODUCTID,NAME,  
               PRODUCTNUMBER,SAFETYSTOCKLEVEL
          FROM SYSTEMA.ADVWORKS.PRODUCT
    

    If we run the table function, it returns the entire product table:

    SELECT * FROM TABLE(DEV.RMTPRODUCT()) PRODUCT
    

    Likewise, to retrieve the customer information from remote SystemB, we create a local UDTF that queries SystemB:

    CREATE OR REPLACE FUNCTION DEV.RMTCUSTOMER()
    RETURNS TABLE
    (CUSTOMERID INT,
     ACCOUNTNUMBER NVARCHAR(32),
     CUSTOMERTYPE NCHAR(1),
     NAME NVARCHAR(60))
    LANGUAGE SQL
    DISALLOW PARALLEL
    DETERMINISTIC
    CARDINALITY 5000
    SET OPTION COMMIT=*NONE
    RETURN
    SELECT C.CUSTOMERID,C.ACCOUNTNUMBER,C.CUSTOMERTYPE,
           COALESCE(S.NAME,I.FIRSTNAME||' '||I.LASTNAME) AS NAME
      FROM SYSTEMB.ADVWORKS.CUSTOMER C
      LEFT JOIN SYSTEMB.ADVWORKS.STORE S ON S.CUSTOMERID=C.CUSTOMERID
                    AND C.CUSTOMERTYPE='S'
      LEFT JOIN SYSTEMB.ADVWORKS.CONTACT I ON I.CONTACTID=C.CUSTOMERID
                    AND C.CUSTOMERTYPE='I'
    

    Finally, the local tables can now be combined with the remote data in a single statement as follows:

    Combine three relational databases in a single SELECT
    CREATE TABLE QTEMP.CUSTOMER_ORDERS AS (
    SELECT SOH.SALESORDERID,SOH.CUSTOMERID,SOH.ORDERDATE,
          C.NAME CUSTOMERNAME,SOD.PRODUCTID,P.NAME PRODUCTNAME,
          SOD.ORDERQTY,SOD.UNITPRICE
      FROM ADVWORKS.SALESORDERHEADER SOH -- Local
      JOIN TABLE(RMTCUSTOMER()) C ON C.CUSTOMERID=SOH.CUSTOMERID 
      -- Remote SystemB
      JOIN ADVWORKS.SALESORDERDETAIL SOD ON SOD.SALESORDERID=
      SOH.SALESORDERID - Local
      JOIN TABLE(RMTPRODUCT()) P ON P.PRODUCTID=SOD.PRODUCTID
       -- Remote SystemA
     WHERE SOH.CustomerId=12314
    ) WITH DATA
    

    And there you have a DB2 for i query that accesses multiple DB2 relational databases.

    A few things to consider:

    • Where possible, specify a cardinality on the table function definition. This value should be the average number of rows the table function can be expected to return.
    • In my simple UDTF examples, I brought back the entire result set because they were small. For larger data sets, add parameters to the table function that can filter the amount of data brought back from the remote server. Remember, table functions are relatively slow performers.
    • UDTFs written in this manner can allow other SQL DML statements (such as an UPDATE) to access multiple databases in a single query (although the UPDATE statement’s target must always be a local table or view.)
    • If you’re familiar with Java and JDBC, you can write a table function that accesses other relational database management systems such as SQL Server, Oracle or MySQL. This flexibility allows a query to reach out beyond the boundaries of DB2.

    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 STORIES

    Copy Data From A Remote DB2 Database Using DB2 For i 7.1

    Execute SQL Statements on DB2 UDB for Windows from the iSeries

    Using DRDA to Execute SQL Statements on Another iSeries



                         Post this story to del.icio.us
                   Post this story to Digg
        Post this story to Slashdot

    Share this:

    • Reddit
    • Facebook
    • LinkedIn
    • Twitter
    • Email

    Tags:

    Sponsored by
    WorksRight Software

    Do you need area code information?
    Do you need ZIP Code information?
    Do you need ZIP+4 information?
    Do you need city name information?
    Do you need county information?
    Do you need a nearest dealer locator system?

    We can HELP! We have affordable AS/400 software and data to do all of the above. Whether you need a simple city name retrieval system or a sophisticated CASS postal coding system, we have it for you!

    The ZIP/CITY system is based on 5-digit ZIP Codes. You can retrieve city names, state names, county names, area codes, time zones, latitude, longitude, and more just by knowing the ZIP Code. We supply information on all the latest area code changes. A nearest dealer locator function is also included. ZIP/CITY includes software, data, monthly updates, and unlimited support. The cost is $495 per year.

    PER/ZIP4 is a sophisticated CASS certified postal coding system for assigning ZIP Codes, ZIP+4, carrier route, and delivery point codes. PER/ZIP4 also provides county names and FIPS codes. PER/ZIP4 can be used interactively, in batch, and with callable programs. PER/ZIP4 includes software, data, monthly updates, and unlimited support. The cost is $3,900 for the first year, and $1,950 for renewal.

    Just call us and we’ll arrange for 30 days FREE use of either ZIP/CITY or PER/ZIP4.

    WorksRight Software, Inc.
    Phone: 601-856-8337
    Fax: 601-856-9432
    Email: software@worksright.com
    Website: www.worksright.com

    Share this:

    • Reddit
    • Facebook
    • LinkedIn
    • Twitter
    • Email

    Sponsored Links

    Linoma Software:  Stop doing FTP the hard way. Take a brief video tour of the GoAnywhere Suite
    Help/Systems:  FREE: Download the IBM i Scheduling Survival Guide
    Four Hundred Monitor Calendar:  Latest info on national conferences, local events, & Webinars

    IT Jungle Store Top Book Picks

    BACK IN STOCK: Easy Steps to Internet Programming for System i: List Price, $49.95

    The iSeries Express Web Implementer's Guide: List Price, $49.95
    The iSeries Pocket Database Guide: List Price, $59
    The iSeries Pocket SQL Guide: List Price, $59
    The iSeries Pocket WebFacing Primer: List Price, $39
    Migrating to WebSphere Express for iSeries: List Price, $49
    Getting Started with WebSphere Express for iSeries: List Price, $49
    The All-Everything Operating System: List Price, $35
    The Best Joomla! Tutorial Ever!: List Price, $19.95

    RJS Nabs Custom App Dev Firm Power7+ Chips Juiced With Faster Clocks, Memory Compression

    Leave a Reply Cancel reply

Volume 12, Number 20 -- August 8, 2012
THIS ISSUE SPONSORED BY:

SEQUEL Software
WorksRight Software
System i Developer

Table of Contents

  • Accessing Multiple DB2 Relational Databases In A Single Query
  • Composing An XML Document From Relational Data, Part 1
  • Admin Alert: The Right Way To Delete User Profiles, Part 2

Content archive

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

Recent Posts

  • POWERUp 2025 –Your Source For IBM i 7.6 Information
  • Maxava Consulting Services Does More Than HA/DR Project Management – A Lot More
  • Guru: Creating An SQL Stored Procedure That Returns A Result Set
  • As I See It: At Any Cost
  • IBM i PTF Guide, Volume 27, Number 19
  • IBM Unveils Manzan, A New Open Source Event Monitor For IBM i
  • Say Goodbye To Downtime: Update Your Database Without Taking Your Business Offline
  • i-Rays Brings Observability To IBM i Performance Problems
  • Another Non-TR “Technology Refresh” Happens With IBM i TR6
  • IBM i PTF Guide, Volume 27, Number 18

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