[英]How to return value from stored procedure
I have a MySql procedure that gets some input arguments and as a result selects a single value like this: 我有一个MySql过程,该过程获取一些输入参数,结果选择了一个像这样的值:
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".
我一直在寻找解决方案,发现的所有解决方案都以“ 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.
对我来说,这不是一个选择-无法更改“ existingStoredProcedure”,因为它已在应用程序的许多部分中使用,因此添加另一个参数将要求我做很多更改。
Is there a way to return a value without adding "out" parameter? 有没有一种方法可以在不添加“ out”参数的情况下返回值? 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 :)
我是一名Java程序员,所以如果mysql存储过程可以“将”选定的行和值“返回”到放置调用的任何实体,那就太好了:)
If a procedure just executes a select
statement, then you can read the results into an instance of ResultSet
. 如果过程仅执行
select
语句,则可以将结果读入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. 现在,从JAVA程序中调用相同的代码。
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 : 参考 :
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.