Share via


방법: SQLSRV 드라이버를 사용하여 입력 및 출력 매개 변수 검색

PHP 드라이버 다운로드

이 항목에서는 SQLSRV 드라이버를 사용하여 1개의 매개 변수가 입력/출력 매개 변수로 정의된 저장 프로시저를 호출하는 방법과 결과를 검색하는 방법을 보여줍니다. 출력 또는 입력/출력 매개 변수를 검색할 때 반환된 매개 변수 값에 액세스하려면 저장 프로시저에서 반환된 모든 결과를 사용해야 합니다.

참고 항목

초기화되거나 null, 날짜/시간또는 스트림 형식으로 업데이트되는 변수는 출력 매개 변수로 사용할 수 없습니다.

예 1

다음 예시에서는 지정된 직원의 사용 가능한 휴가 시간에서 사용한 휴가 시간을 차감하는 저장 프로시저를 호출합니다. 사용한 휴가 시간($vacationHrs)을 나타내는 변수는 저장 프로시저에 입력 매개 변수로 전달됩니다. 사용 가능한 휴가 시간을 업데이트한 후 저장 프로시저는 동일한 매개 변수를 사용하여 잔여 휴가 시간을 반환합니다.

참고 항목

$vacationHrs를 4로 초기화하면 반환되는 PHPTYPE이 정수로 설정됩니다. 데이터 형식 무결성을 보장하려면 저장 프로시저를 호출하기 전에 입출력 매개 변수를 초기화하거나 원하는 PHPTYPE을 지정해야 합니다. PHPTYPE을 지정하는 방법에 대한 자세한 내용은 방법: PHP 데이터 형식 지정을 참조하세요.

저장 프로시저는 두 개의 결과를 반환하므로 출력 매개 변수의 값을 사용할 수 있도록 하려면 저장 프로시저가 실행된 후에 sqlsrv_next_result를 호출해야 합니다. sqlsrv_next_result를 호출한 후 $vacationHrs에는 저장 프로시저에서 반환된 출력 매개 변수의 값이 들어 있습니다.

참고 항목

권장되는 방법은 정식 구문을 사용하여 저장 프로시저를 호출하는 것입니다. 정식 구문에 대한 자세한 내용은 저장 프로시저 호출을 참조하세요.

이 예시에서는 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));  
}  
  
/* Drop the stored procedure if it already exists. */  
$tsql_dropSP = "IF OBJECT_ID('SubtractVacationHours', 'P') IS NOT NULL  
                DROP PROCEDURE SubtractVacationHours";  
$stmt1 = sqlsrv_query( $conn, $tsql_dropSP);  
if( $stmt1 === false )  
{  
     echo "Error in executing statement 1.\n";  
     die( print_r( sqlsrv_errors(), true));  
}  
  
/* Create the stored procedure. */  
$tsql_createSP = "CREATE PROCEDURE SubtractVacationHours  
                        @EmployeeID int,  
                        @VacationHrs smallint OUTPUT  
                  AS  
                  UPDATE HumanResources.Employee  
                  SET VacationHours = VacationHours - @VacationHrs  
                  WHERE EmployeeID = @EmployeeID;  
                  SET @VacationHrs = (SELECT VacationHours  
                                      FROM HumanResources.Employee  
                                      WHERE EmployeeID = @EmployeeID)";  
  
$stmt2 = sqlsrv_query( $conn, $tsql_createSP);  
if( $stmt2 === false )  
{  
     echo "Error in executing statement 2.\n";  
     die( print_r( sqlsrv_errors(), true));  
}  
  
/*--------- The next few steps call the stored procedure. ---------*/  
  
/* Define the Transact-SQL query. Use question marks (?) in place of  
the parameters to be passed to the stored procedure */  
$tsql_callSP = "{call SubtractVacationHours( ?, ?)}";  
  
/* Define the parameter array. By default, the first parameter is an  
INPUT parameter. The second parameter is specified as an INOUT  
parameter. Initializing $vacationHrs to 8 sets the returned PHPTYPE to  
integer. To ensure data type integrity, output parameters should be  
initialized before calling the stored procedure, or the desired  
PHPTYPE should be specified in the $params array.*/  
  
$employeeId = 4;  
$vacationHrs = 8;  
$params = array(   
                 array($employeeId, SQLSRV_PARAM_IN),  
                 array(&$vacationHrs, SQLSRV_PARAM_INOUT)  
               );  
  
/* Execute the query. */  
$stmt3 = sqlsrv_query( $conn, $tsql_callSP, $params);  
if( $stmt3 === false )  
{  
     echo "Error in executing statement 3.\n";  
     die( print_r( sqlsrv_errors(), true));  
}  
  
/* Display the value of the output parameter $vacationHrs. */  
sqlsrv_next_result($stmt3);  
echo "Remaining vacation hours: ".$vacationHrs;  
  
/*Free the statement and connection resources. */  
sqlsrv_free_stmt( $stmt1);  
sqlsrv_free_stmt( $stmt2);  
sqlsrv_free_stmt( $stmt3);  
sqlsrv_close( $conn);  
?>  

참고 항목

입력/출력 매개 변수를 bigint 유형에 바인딩할 때 값이 integer의 범위를 벗어날 수 있는 경우 해당 SQL 필드 유형을 SQLSRV_SQLTYPE_BIGINT로 지정해야 합니다. 그렇지 않으면 "값이 범위를 벗어났습니다" 예외가 발생할 수 있습니다.

예시 2

이 코드 샘플에서는 큰 bigint 값을 입력/출력 매개 변수로 바인딩하는 방법을 보여줍니다.

<?php
$serverName = "(local)";
$connectionInfo = array("Database"=>"testDB");  
$conn = sqlsrv_connect($serverName, $connectionInfo);  
if ($conn === false) {  
    echo "Could not connect.\n";  
    die(print_r(sqlsrv_errors(), true));  
}  

// Assume the stored procedure spTestProcedure exists, which retrieves a bigint value of some large number
// e.g. 9223372036854
$bigintOut = 0;
$outSql = "{CALL spTestProcedure (?)}";
$stmt = sqlsrv_prepare($conn, $outSql, array(array(&$bigintOut, SQLSRV_PARAM_INOUT, null, SQLSRV_SQLTYPE_BIGINT)));
sqlsrv_execute($stmt);
echo "$bigintOut\n";   // Expect 9223372036854

sqlsrv_free_stmt($stmt);  
sqlsrv_close($conn);  

?>

참고 항목

방법: SQLSRV 드라이버를 사용하여 매개 변수 방향 지정

방법: SQLSRV 드라이버를 사용하여 출력 매개 변수 검색

데이터 검색