次の方法で共有


複数の結果セットを操作する方法

SQL Server Driver for PHP には、ステートメントの次の結果 (結果セット、行数、または出力パラメータ) をアクティブにするための sqlsrv_next_result 関数が用意されています。このトピックでは、sqlsrv_next_result を使用してバッチ クエリの 1 つの結果から次の結果に移動する方法を示します。ストアド プロシージャから返される出力パラメータを取得する例については、「sqlsrv_next_result」を参照してください。

次の例では、指定した製品 ID に関する製品レビュー情報を取得するバッチ クエリを実行し、その製品のレビューを挿入した後、再度、指定した製品 ID に関する製品レビュー情報を取得します。新しく挿入された製品レビューは、バッチ クエリの最終的な結果セットに含まれます。この例では sqlsrv_next_result を使用して、バッチ クエリの 1 つの結果から次の結果に移動します。

注意

バッチ クエリやストアド プロシージャから返される最初の (または唯一の) 結果は、sqlsrv_next_result を呼び出さなくてもアクティブになります。

この例では、AdventureWorks データベースの Purchasing.ProductReview テーブルを使用するため、このデータベースがサーバーにインストールされていることを前提としています。この例をコマンド ラインから実行した場合、すべての出力はコンソールに書き込まれます。

<?php
/* Connect to the local server using Windows Authentication and
specify the AdventureWorks database as the database in use. */
$serverName = "(local)";
$connectionInfo = array( "Database"=>"AdventureWorks");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false )
{
     echo "Could not connect.\n";
     die( print_r( sqlsrv_errors(), true));
}

/* Define the batch query. */
$tsql = "--Query 1
         SELECT ProductID, ReviewerName, Rating 
         FROM Production.ProductReview 
         WHERE ProductID=?;

         --Query 2
         INSERT INTO Production.ProductReview (ProductID, 
                                               ReviewerName, 
                                               ReviewDate, 
                                               EmailAddress, 
                                               Rating)
         VALUES (?, ?, ?, ?, ?);

         --Query 3
         SELECT ProductID, ReviewerName, Rating 
         FROM Production.ProductReview 
         WHERE ProductID=?;";

/* Assign parameter values and execute the query. */
$params = array(798, 
                798, 
                'CustomerName', 
                '2008-4-15', 
                'test@customer.com', 
                3, 
                798 );
$stmt = sqlsrv_query($conn, $tsql, $params);
if( $stmt === false )
{
     echo "Error in statement execution.\n";
     die( print_r( sqlsrv_errors(), true));
}

/* Retrieve and display the first result. */
echo "Query 1 result:\n";
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC ))
{
     print_r($row);
}

/* Move to the next result of the batch query. */
sqlsrv_next_result($stmt);

/* Display the result of the second query. */
echo "Query 2 result:\n";
echo "Rows Affected: ".sqlsrv_rows_affected($stmt)."\n";

/* Move to the next result of the batch query. */
sqlsrv_next_result($stmt);

/* Retrieve and display the third result. */
echo "Query 3 result:\n";
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC ))
{
     print_r($row);
}

/* Free statement and connection resources. */
sqlsrv_free_stmt( $stmt );
sqlsrv_close( $conn );
?>

参照

処理手順

サンプル アプリケーション

概念

ドキュメントのコード例について

その他のリソース

データの取得
データの更新 (SQL Server Driver for PHP)
API リファレンス (SQL Server Driver for PHP)