Using different databases in same COBOL program

I need to get info from tables in database X, which the COBOL program is connected to, and insert info from them to a table in database Y, which the program is not connected to.  Is there a way to do this in one program?  If yes, how do I reference the copybook for the table in database Y.  If I need to connect to Y, what does that do to the connection with X?  Thanks.

  • You can connect to two different databases within the same program by using a named connection and then switch between them using the SET CONNECTION statement.

    Example from the docs:

     

     

         EXEC SQL CONNECT TO "srv1" AS server1 USER "sa." END-EXEC
         EXEC SQL CONNECT TO "srv2" AS server2 USER "sa." END-EXEC
      
    * server2 is the current connection
         EXEC SQL CREATE TABLE phil1
            (charbit    CHAR(5))
         END-EXEC
    
         IF SQLCODE NOT = ZERO
            DISPLAY 'Error: Could not create table.'
            DISPLAY SQLERRMC
            DISPLAY SQLERRML
            EXEC SQL DISCONNECT ALL END-EXEC
            STOP RUN
         END-IF
    
         EXEC SQL INSERT INTO phil1 VALUES('hello') END-EXEC
    
         IF SQLCODE NOT = ZERO
            DISPLAY 'Error: Could not insert data.'
            DISPLAY SQLERRMC
            DISPLAY SQLERRML
            EXEC SQL DISCONNECT ALL END-EXEC
            STOP RUN
          END-IF
    
    * set the current connection to server1
         EXEC SQL SET CONNECTION server1 END-EXEC
         EXEC SQL
            SELECT first_name
               INTO :fname
               FROM staff
               WHERE staff_id = 10
         END-EXEC
    
         DISPLAY fname ' says ' WITH NO ADVANCING
    
    * set the current connection back to server2
         EXEC SQL SET CONNECTION server2 END-EXEC
         EXEC SQL
            SELECT charbit
               INTO :fname
               WHERE charbit = 'hello'
               FROM phil1
         END-EXEC
    
         DISPLAY fname
         EXEC SQL DISCONNECT server1 END-EXEC
         EXEC SQL DISCONNECT server2 END-EXEC
         STOP RUN