방법: SQLSRV 드라이버를 사용하여 오류 및 경고 처리

PHP 드라이버 다운로드

기본적으로 SQLSRV 드라이버는 경고를 오류로 처리하며, 오류 또는 경고를 생성하는 sqlsrv 함수를 호출하면 false를 반환합니다. 이 항목에서는 이 기본 동작을 해제하는 방법과 경고를 오류와 별도로 처리하는 방법을 보여줍니다.

참고 항목

경고를 오류로 처리하는 기본 동작에는 몇 가지 예외가 있습니다. SQLSTATE 값 01000, 01001, 01003 및 01S02에 해당하는 경고는 오류로 처리되지 않습니다.

예시

다음 코드 예시에서는 두 개의 사용자 정의 함수인 DisplayErrorsDisplayWarnings를 사용하여 오류 및 경고를 처리합니다. 이 예시에서는 다음을 수행하여 경고 및 오류를 개별적으로 처리하는 방법을 보여줍니다.

  1. 경고를 오류로 처리하는 기본 동작을 해제합니다.

  2. 직원의 휴가 시간을 업데이트하고 잔여 휴가 시간을 출력 매개 변수로 반환하는 저장 프로시저를 만듭니다. 직원의 사용 가능한 휴가 시간이 0보다 작으면 저장 프로시저에 경고가 출력됩니다.

  3. 각 직원에 대한 저장 프로시저를 호출하여 여러 직원의 휴가 시간을 업데이트하고 발생하는 모든 경고 및 오류에 해당하는 메시지를 표시합니다.

  4. 각 직원의 잔여 휴가 시간을 표시합니다.

sqlsrv 함수(sqlsrv_configure)에 대한 첫 번째 호출에서 경고는 오류로 처리됩니다. 경고는 오류 컬렉션에 추가되므로 오류와 별도로 경고를 확인할 필요가 없습니다. 그러나 이후 sqlsrv 함수를 호출할 때 경고는 오류로 취급되지 않으므로 경고와 오류를 명시적으로 확인해야 합니다.

또한 sqlsrv 함수에 대한 각 호출 이후 예시 코드가 오류를 확인합니다. 이것이 권장되는 방법입니다.

이 예시에서는 SQL Server 및 AdventureWorks 데이터베이스가 로컬 컴퓨터에 설치된 것으로 가정합니다. 모든 출력은 명령줄에서 예시가 실행될 때 콘솔에 기록됩니다. 이 예시를 새로 설치한 AdventureWorks 데이터베이스에 대해 실행하면 경고 3개와 오류 2개가 발생합니다. 처음 두 개의 경고는 데이터베이스에 연결할 때 표시되는 표준 경고입니다. 세 번째 경고는 직원의 사용 가능한 휴가 시간이 0보다 작은 값으로 업데이트되기 때문에 발생합니다. 직원의 사용 가능한 휴가 시간이 -40시간 미만의 값으로 업데이트되어 테이블에 대한 제약 조건을 위반하기 때문에 오류가 발생합니다.

<?php  
/* Turn off the default behavior of treating errors as warnings.  
Note: Turning off the default behavior is done here for demonstration  
purposes only. If setting the configuration fails, display errors and  
exit the script. */  
if( sqlsrv_configure("WarningsReturnAsErrors", 0) === false)  
{  
     DisplayErrors();  
     die;  
}  
  
/* 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 the connection fails, display errors and exit the script. */  
if( $conn === false )  
{  
     DisplayErrors();  
     die;  
}  
/* Display any warnings. */  
DisplayWarnings();  
  
/* Drop the stored procedure if it already exists. */  
$tsql1 = "IF OBJECT_ID('SubtractVacationHours', 'P') IS NOT NULL  
                DROP PROCEDURE SubtractVacationHours";  
$stmt1 = sqlsrv_query($conn, $tsql1);  
  
/* If the query fails, display errors and exit the script. */  
if( $stmt1 === false)  
{  
     DisplayErrors();  
     die;  
}  
/* Display any warnings. */  
DisplayWarnings();  
  
/* Free the statement resources. */  
sqlsrv_free_stmt( $stmt1 );  
  
/* Create the stored procedure. */  
$tsql2 = "CREATE PROCEDURE SubtractVacationHours  
                  @EmployeeID int,  
                  @VacationHours smallint OUTPUT  
              AS  
                  UPDATE HumanResources.Employee  
                  SET VacationHours = VacationHours - @VacationHours  
                  WHERE EmployeeID = @EmployeeID;  
                  SET @VacationHours = (SELECT VacationHours    
                                       FROM HumanResources.Employee  
                                       WHERE EmployeeID = @EmployeeID);  
              IF @VacationHours < 0   
              BEGIN  
                PRINT 'WARNING: Vacation hours are now less than zero.'  
              END;";  
$stmt2 = sqlsrv_query( $conn, $tsql2 );  
  
/* If the query fails, display errors and exit the script. */  
if( $stmt2 === false)  
{  
     DisplayErrors();  
     die;  
}  
/* Display any warnings. */  
DisplayWarnings();  
  
/* Free the statement resources. */  
sqlsrv_free_stmt( $stmt2 );  
  
/* Set up the array that maps employee ID to used vacation hours. */  
$emp_hrs = array (7=>4, 8=>5, 9=>8, 11=>50);  
  
/* Initialize variables that will be used as parameters. */  
$employeeId = 0;  
$vacationHrs = 0;  
  
/* Set up the parameter array. */  
$params = array(  
                 array(&$employeeId, SQLSRV_PARAM_IN),  
                 array(&$vacationHrs, SQLSRV_PARAM_INOUT)  
                );  
  
/* Define and prepare the query to subtract used vacation hours. */  
$tsql3 = "{call SubtractVacationHours(?, ?)}";  
$stmt3 = sqlsrv_prepare($conn, $tsql3, $params);  
  
/* If the statement preparation fails, display errors and exit the script. */  
if( $stmt3 === false)  
{  
     DisplayErrors();  
     die;  
}  
/* Display any warnings. */  
DisplayWarnings();  
  
/* Loop through the employee=>vacation hours array. Update parameter  
 values before statement execution. */  
foreach(array_keys($emp_hrs) as $employeeId)  
{  
     $vacationHrs = $emp_hrs[$employeeId];  
     /* Execute the query.  If it fails, display the errors. */  
     if( sqlsrv_execute($stmt3) === false)  
     {  
          DisplayErrors();  
          die;  
     }  
     /* Display any warnings. */  
     DisplayWarnings();  
  
     /*Move to the next result returned by the stored procedure. */  
     if( sqlsrv_next_result($stmt3) === false)  
     {  
          DisplayErrors();  
          die;  
     }  
     /* Display any warnings. */  
     DisplayWarnings();  
  
     /* Display updated vacation hours. */  
     echo "EmployeeID $employeeId has $vacationHrs ";  
     echo "remaining vacation hours.\n";  
}  
  
/* Free the statement and connection resources. */  
sqlsrv_free_stmt( $stmt3 );  
sqlsrv_close( $conn );  
  
/* ------------- Error Handling Functions --------------*/  
function DisplayErrors()  
{  
     $errors = sqlsrv_errors(SQLSRV_ERR_ERRORS);  
     foreach( $errors as $error )  
     {  
          echo "Error: ".$error['message']."\n";  
     }  
}  
  
function DisplayWarnings()  
{  
     $warnings = sqlsrv_errors(SQLSRV_ERR_WARNINGS);  
     if(!is_null($warnings))  
     {  
          foreach( $warnings as $warning )  
          {  
               echo "Warning: ".$warning['message']."\n";  
          }  
     }  
}  
?>  

참고 항목

방법: SQLSRV 드라이버를 사용하여 오류 및 경고 처리 구성

SQLSRV 드라이버 API 참조