다음을 통해 공유


방법: 쿼리 다중 실행

이 항목의 예에서는 SQL Server Driver for PHP를 사용하여 준비된 문을 여러 번 실행하는 방법에 대해 설명합니다. sqlsrv_preparesqlsrv_execute 조합을 사용하면 문을 서버에서 한 번 컴파일한 다음 여러 매개 변수 값을 사용하여 여러 번 실행할 수 있습니다.

참고

일회성 쿼리의 경우에는 sqlsrv_query를 사용하는 것이 좋습니다.

변수를 매개 변수로 사용하는 문을 준비하는 경우 변수가 문에 바인딩됩니다. 즉, 변수 값을 업데이트하는 경우 다음에 문을 실행하면 업데이트된 매개 변수 값을 사용하여 문이 실행됩니다.

다음 예제에서는 문을 준비한 다음 다른 매개 변수 값을 사용하여 다시 실행하는 방법에 대해 설명합니다. 먼저 AdventureWorks 데이터베이스에서 Sales.SalesOrderDetail 테이블의 OrderQty 열을 업데이트합니다. 업데이트가 발생한 후에는 성공적으로 업데이트되었는지 확인하기 위해 데이터베이스를 쿼리합니다. 이 예제에서는 SQL Server와 AdventureWorks 데이터베이스가 로컬 컴퓨터에 설치되어 있다고 가정합니다. 명령줄에서 이 예제를 실행하면 모든 출력이 콘솔에 기록됩니다.

<?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 parameterized query. */
$tsql = "UPDATE Sales.SalesOrderDetail
         SET OrderQty = ?
         WHERE SalesOrderDetailID = ?";

/* Initialize parameters and prepare the statement. Variables $qty
and $id are bound to the statement, $stmt1. */
$qty = 0; $id = 0;
$stmt1 = sqlsrv_prepare( $conn, $tsql, array( &$qty, &$id));
if( $stmt1 )
{
     echo "Statement 1 prepared.\n";
} 
else 
{
     echo "Error in statement preparation.\n";
     die( print_r( sqlsrv_errors(), true));
}

/* Set up the SalesOrderDetailID and OrderQty information. This array
maps the order ID to order quantity in key=>value pairs. */
$orders = array( 1=>10, 2=>20, 3=>30);

/* Execute the statement for each order. */
foreach( $orders as $id => $qty)
{
     // Because $id and $qty are bound to $stmt1, their updated
     // values are used with each execution of the statement. 
     if( sqlsrv_execute( $stmt1) === false )
     {
          echo "Error in statement execution.\n";
          die( print_r( sqlsrv_errors(), true));
     }
}
echo "Orders updated.\n";

/* Free $stmt1 resources.  This allows $id and $qty to be bound to a different statement.*/
sqlsrv_free_stmt( $stmt1);

/* Now verify that the results were successfully written by selecting 
the newly inserted rows. */
$tsql = "SELECT OrderQty 
         FROM Sales.SalesOrderDetail 
         WHERE SalesOrderDetailID = ?";

/* Prepare the statement. Variable $id is bound to $stmt2. */
$stmt2 = sqlsrv_prepare( $conn, $tsql, array( &$id));
if( $stmt2 )
{
     echo "Statement 2 prepared.\n";
} 
else 
{
     echo "Error in statement preparation.\n";
     die( print_r( sqlsrv_errors(), true));
}

/* Execute the statement for each order. */
foreach( array_keys($orders) as $id)
{
     /* Because $id is bound to $stmt2, its updated value 
        is used with each execution of the statement. */
     if( sqlsrv_execute( $stmt2))
     {
          sqlsrv_fetch( $stmt2);
          $quantity = sqlsrv_get_field( $stmt2, 0);
          echo "Order $id is for $quantity units.\n";
     }
     else
     {
          echo "Error in statement execution.\n";
          die( print_r( sqlsrv_errors(), true));
     }
}

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

많은 양의 정보를 쓰고 읽기 위한 대체 방법은 SQL 문 일괄 처리(Batches of SQL Statements)BULK INSERT를 참조하십시오.

참고 항목

태스크

방법 매개 변수가 있는 쿼리 수행
방법: 여러 개의 결과 집합 사용

관련 자료

디자인 고려 사항
데이터 검색
데이터 업데이트(SQL Server Driver for PHP)
API 참조(SQL Server Driver for PHP)