Reputation: 2956
I have a MySql procedure that gets some input arguments and as a result selects a single value like this:
declare rez int;
///
...some other code...
///
select rez;
Now, i want to call that stored procedure from another stored procedure and obtain "selected" value. I tried something like this:
declare myVar int;
set myVar = call existingStoredProcedure();
but it won't do. How should i do this? I was googling for the solution and all solutions i found begin with something like "create >existingStoredProcedure< with OUT param". For me that's not an option - "existingStoredProcedure" can't be changed as it's being used in many parts of the application so adding another parameter would ask for a lot of changes i presume.
Is there a way to return a value without adding "out" parameter? I'm a Java programmer so it would be very nice if mysql stored procedure could just "return" selected rows and values to any entity that placed a call :)
Upvotes: 0
Views: 317
Reputation: 24012
If a procedure just executes a select
statement, then you can read the results into an instance of ResultSet
.
CallableStatement cst = con.prepareCall( "{call sql_procedureName()}" );
ResultSet rs = cst.executeQuery();
Working Example:
Let us say, you have a stored procedure that returns current date and current day name.
drop procedure if exists today;
create procedure today()
select @dt:=current_date as today, dayname( @dt ) as dayname;
Now, call the same from JAVA program.
CallableStatement cst = con.prepareCall( "{call today()}" );
ResultSet rs = cst.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
System.out.println( "Column Count: " + columnCount );
for ( int i = 1; i <= columnCount; i++ ) {
System.out.print( ( i == 1 ? "Column Names: " : ", " )
+ rsmd.getColumnLabel( i ) );
} // for each column
System.out.println();
int rowNumber = 1;
while( rs.next() ) {
for ( int i = 1; i <= columnCount; i++ ) {
System.out.print( ( i == 1 ? ( "Record " + rowNumber++ + ": " ) : ", " )
+ rsmd.getColumnLabel( i ) + ": " + rs.getString( i ) );
} // for each column
System.out.println();
} // while rs
Output:
Column Count: 2
Column Names: today, dayname
Record 1: today: 2014-04-03, dayname: Thursday
Refer to:
Upvotes: 1