fetching_multiple_from_sp.cpp

This example shows how to fetch multiple result sets from a stored procedure.



// *********************************************************************
// Copyright 1994-2008 iAnywhere Solutions, Inc.  All rights reserved.
// This sample code is provided AS IS, without warranty or liability
// of any kind.
//
// You may use, reproduce, modify and distribute this sample code
// without limitation, on the condition that you retain the foregoing
// copyright notice and disclaimer as to the original iAnywhere code.
//
// *********************************************************************
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "sacapidll.h"

int main( )
{
    SQLAnywhereInterface  api;
    a_sqlany_connection * conn;
    a_sqlany_stmt       * stmt;
    unsigned int          max_api_ver;

    if( !sqlany_initialize_interface( &api, NULL ) ) {
        printf( "Could not initialize the interface!\n" );
        exit( 0 );
    }

    if( !api.sqlany_init( "MyApp", SQLANY_CURRENT_API_VERSION, &max_api_ver )) {
        printf( "Failed to initialize the interface! Supported version=%d\n", max_api_ver );
        sqlany_finalize_interface( &api );
        return -1;
    }

    /* A connection object needs to be created first */
    conn = api.sqlany_new_connection();

    if( !api.sqlany_connect( conn, "uid=dba;pwd=sql" ) ) {
        api.sqlany_free_connection( conn );
        api.sqlany_fini();
        sqlany_finalize_interface( &api );
        exit( -1 );
    }

    printf( "Connected successfully!\n" );

    api.sqlany_execute_immediate( conn, "drop procedure myproc" );
    api.sqlany_execute_immediate( conn,
            "create procedure myproc( ) \n"
            "begin              \n"
            "    select 1, 2;   \n"
            "    select 3, 4, 5;\n"
            "end                \n" );


    if( (stmt = api.sqlany_execute_direct( conn, "call myproc()" )) != NULL ) {
        do {
            /* fetch one row at a time */
            while( api.sqlany_fetch_next( stmt ) ) {

                /* sqlany_num_cols() will be updated every time the result set shape changes */
                for( int I = 0; I < api.sqlany_num_cols( stmt ); I++ ) {
                    /* process data here ... */
                }
            }
            /* Check to see if there are other result sets */
        } while( api.sqlany_get_next_result( stmt ) );

        /* Must free the result set object when done with it */
        api.sqlany_free_stmt( stmt );
    }
    api.sqlany_disconnect( conn );

    /* Must free the connection object or there will be a memory leak */
    api.sqlany_free_connection( conn );

    api.sqlany_fini();

    sqlany_finalize_interface( &api );

    return 0;
}