【问题标题】:Getting output of MS stored procedure on php call在 php 调用 (sqlsrv) 上获取 MS 存储过程的输出
【发布时间】:2012-01-11 10:30:51
【问题描述】:

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

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

【问题讨论】:

  • 答案很简单 sqlsrv_fetch_array($stmt3),我没有删除问题的原因是我没有看到任何与此代码类似的帖子。所以我把它留给其他想要使用 SP 和 PHP 的人

标签: php sql sql-server


【解决方案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()),不止一行(在这种情况下,您必须使用 while 循环并在循环中调用 sqlsrv_fetch()),或多个结果集(在这种情况下,您将需要使用 sqlsrv_next_result() 的 while 循环)。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 这仍然返回resounce id。除了我使用这个“插入表(ColumnName)OUTPUT INSERTED.ID Values('SomeColumnValue')”而不是存储过程。 sql中的OUTPUT会像存储过程一样返回吗?
    猜你喜欢
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    相关资源
    最近更新 更多