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

时间:2011-12-02 11:21:06

标签: php sql sql-server

我正在使用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); 

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

2 个答案:

答案 0 :(得分:3)

假设存储过程使用单个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
     // ...
}

答案 1 :(得分:1)

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

From the example code in the manual for 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()),一行(在这种情况下,您将不得不在循环中调用sqlsrv_fetch()使用while循环),或者多个结果集(在这种情况下,您需要使用{{3}的while循环})。