//  Source File Name: Outsrv.sqlj  1.7
//  
//   Licensed Materials -- Property of IBM 
//  
//   (c) Copyright International Business Machines Corporation, 1998, 1999. 
//       All Rights Reserved. 
//  
//   US Government Users Restricted Rights - 
//   Use, duplication or disclosure restricted by 
//   GSA ADP Schedule Contract with IBM Corp. 

//   Sample Program Outsrv - SQLJ Output Stored Procedure 

//   Steps to run the sample: 
//   (1) create and populate the SAMPLE database (db2sampl) 
//   (2) (n)make Outsrv 
//   (3) (n)make Outcli 
//   (4) run Outcli 

//   NOTES: (1) The jdk11_path database manager configuration parameter must 
//              be set 
//          (2) The CLASSPATH and shared library path environment variables 
//              must be set, as for any JDBC application. 
//          (3) Visit http://www.software.ibm.com/data/db2/java 
//              for current DB2 Java information 

//  For more information about this sample, refer to the README file. 

//  For more information on Programming in Java, refer to the  
//  "Programming in Java" section of the Application Development Guide. 

//  For more information on creating stored procedures, refer to the  
//  "Writing Stored Procedures" section of the Application Development Guide. 

//  For more information on building and running Java programs for DB2, 
//  refer to the "Building Java Applets and Applications" section of the  
//  Application Building Guide. 

//  For more information on the SQL language, refer to the SQL Reference. 

//   Class Outsrv contains one method: 
//   (1) outputStoredProcedure: stored procedure body 

import java.sql.*;              //  JDBC classes 
import sqlj.runtime.*;
import sqlj.runtime.ref.*;

#sql iterator Outsrv_Cursor1 (double salary) ;

// ///// 
//  Java stored procedure is in this class 
// ///// 
public class Outsrv
{   //  (1) stored procedure body  
    public static void outputStoredProcedure (          /* :rk.2:erk. */
                                   double[] medianSalary) throws Exception
    {   try
        {   
            //  Declare Variables 
            Outsrv_Cursor1  cursor1;
            short           numRecords;
            int             counter = 0;

            //  Determine the Total Number of Records 
            #sql { SELECT COUNT(*) INTO :numRecords FROM STAFF };   /* :rk.3:erk. */
  
            //  Prepare a Statement to Obtain and Order all Salaries 
            #sql cursor1 = { SELECT salary FROM STAFF ORDER BY salary };

            //  Fetch Salaries until the Median Salary is Obtained 
            while (counter < numRecords/2 + 1)                      /* :rk.4:erk. */
            {   cursor1.next();
                counter++;
            }
            //  set value for the output parameter                   /* :rk.5:erk. */ 
            medianSalary[0] = cursor1.salary(); 
            cursor1.close();
        }
        catch (Exception e)
        {   throw e; 
        }
    }
}