在php调用中获取MS存储过程的输出


Getting output of MS stored procedure on php call

我使用php的sqlsrv ms驱动程序,它工作得很好(用普通查询测试)。我还通过运行一个存储过程来更新表数据来测试它,它也可以工作。

现在我想用它来运行一个存储过程,并且我想检索响应。如何做到这一点?

$server = "...the server address...";
$options = array("UID"=>"...the username...","PWD"=>"...the password...",
  "Database" => "...the database..."
  );
$conn = sqlsrv_connect($server, $options);
if ($conn === false) {die("<pre>".print_r(sqlsrv_errors(), true));}
$tsql_callSP = "{call ...the stored proc...( ?, ?)}";
$params = array( 
                 array("...first value in...", SQLSRV_PARAM_IN),
                 array("...second value in...", SQLSRV_PARAM_IN)
               );
$stmt3 = sqlsrv_query( $conn, $tsql_callSP, $params);
if( $stmt3 === false )
{
     echo "Error in executing statement 3.'n";
     die( print_r( sqlsrv_errors(), true));
}
print_r( $stmt3); //attempting to print the return but all i get is Resource id #3
echo "test echo";
sqlsrv_free_stmt( $stmt3);
sqlsrv_close( $conn); 

我知道我可以使用输出参数,但是我总是会从存储过程中接收多个值。

假设存储过程用一条SELECT语句返回一个表的内容,使用它的输出应该像使用sqlsrv_query的结果一样简单,就像使用任何其他选择查询结果一样(即对结果使用sqlsrv_fetch_object/array)!因此,存储过程看起来像这样:

CREATE STORED PROCEDURE test
AS
    -- do some other stuff here
    -- ...
    SELECT * FROM test
GO

在php中:

// establish db connection, initialize
// ...
$sql = "{call test}"
$result = sqlsrv_query($conn, $sql);
while (sqlsrv_fetch_object($result))
{
     // do something with the data
     // ...
}

您需要调用sqlsrv_fetch()sqlsrv_get_field()来从返回的语句中获取数据。

手册中sqlsrv_get_field的示例代码:

$stmt = sqlsrv_query( $conn, $tsql);
if( $stmt === false )
{
     echo "Error in statement preparation/execution.'n";
     die( print_r( sqlsrv_errors(), true));
}
/* Make the first row of the result set available for reading. */
if( sqlsrv_fetch( $stmt ) === false )
{
     echo "Error in retrieving row.'n";
     die( print_r( sqlsrv_errors(), true));
}
/* Note: Fields must be accessed in order.
Get the first field of the row. Note that no return type is
specified. Data will be returned as a string, the default for
a field of type nvarchar.*/
$name = sqlsrv_get_field( $stmt, 0);
echo "$name: ";

除此之外,我不知道当你说你会收到多个值是否你的意思是会有多个字段在一行(在这种情况下,你会想要更多调用sqlsrv_get_field()),超过一行(在这种情况下,你将不得不使用while循环调用sqlsrv_fetch()循环),或一个以上的结果集(在这种情况下,你会想要一个while循环使用sqlsrv_next_result())。