从存储过程调用中返回变量作为变量的输出值

时间:2019-02-06 20:14:38

标签: php sql db2

我当前正在运行一个存储过程,该过程可以成功运行,但是在调用一个单独的过程之后,我想返回V_R_ID的值作为要存储在PHP中的输出值

因此在此示例中:

P1 : BEGIN ATOMIC

DECLARE V_H_ID INTEGER DEFAULT 0 ;
DECLARE V_R_ID VARCHAR ( 20 ) ;
DECLARE V_TIMESTAMP TIMESTAMP ;

DECLARE C_NAME VARCHAR ( 45 ) DEFAULT 'EMAIL' ;

SELECT CAST ( NEXT VALUE FOR SCHEMA . H_ID_SEQUENCE AS VARCHAR ( 20 ) )
INTO V_R_ID
FROM SYSIBM . SYSDUMMY1 ;

CALL PROCEDURESCHEMA . INSERT_TYPE ( 
V_R_ID
, C_NAME
, IN_DATA
, NULL
, NULL ) ;

/*Here I'd like to declare V_R_ID as an output of RETURN_ID */

END P1 

如何正确执行此操作,以便在PHP中调用此过程之后,可以将RETURN_ID设置为php变量$returnID

1 个答案:

答案 0 :(得分:1)

考虑从DB2 docs声明输出参数:

  

仅输出参数,该参数将值从存储过程返回到调用程序。

CREATE PROCEDURE myProc (OUT V_R_ID  VARCHAR (20))

   LANGUAGE SQL 

P1 : BEGIN ATOMIC

   DECLARE V_H_ID INTEGER DEFAULT 0 ;
   DECLARE V_R_ID VARCHAR ( 20 ) ;
   DECLARE V_TIMESTAMP TIMESTAMP ;

   DECLARE C_NAME VARCHAR ( 45 ) DEFAULT 'EMAIL' ;

   SELECT CAST ( NEXT VALUE FOR SCHEMA . H_ID_SEQUENCE AS VARCHAR ( 20 ) )
   INTO V_R_ID
   FROM SYSIBM . SYSDUMMY1 ;

   CALL PROCEDURESCHEMA . INSERT_TYPE ( 
      V_R_ID
    , C_NAME
    , IN_DATA
    , NULL
    , NULL ) ;

END P1 

然后在PHP中,使用PDO prepared statement,使用?占位符调用该过程并将其绑定到PHP变量:

$dbh = new PDO("ibm:DRIVER={IBM DB2 ODBC DRIVER};DATABASE=****;" .
               "HOSTNAME=##.##.##.###;PORT=####;PROTOCOL=TCPIP;", "user", "pass");

$stmt = $dbh->prepare("CALL myProc(?)"); 
$stmt->bindParam(1, $return_id, PDO::PARAM_STR, 20); 
$stmt->execute();

echo $return_id;

类似但略有不同,使用PHP的IBM DB2 module连接绑定参数将变量命名为字符串名称:

$conn = db2_connect($database, $user, $password);

$stmt = db2_prepare($conn, "CALL myProc(?)");
db2_bind_param($stmt, 1, "return_id", DB2_PARAM_OUT);
db2_execute($stmt);

echo $return_id;