이 항목에서는 SQL Server Driver for PHP를 사용할 때 결과 집합이 비어 있는지 확인하는 방법을 보여 줍니다.
참고
SQL Server Driver for PHP 1.1 버전을 사용할 경우 sqlsrv_has_rows를 사용하여 결과 집합에 행이 있는지 확인할 수 있습니다.
SQL Server Driver for PHP 1.0 버전에서 문의 결과 집합이 비어 있는지 확인하기 위해 권장되는 방법은 문에서 sqlsrv_fetch, sqlsrv_fetch_array 또는 sqlsrv_fetch_object를 호출하여 반환된 값을 검사하는 것입니다. 활성 결과 집합에 결과가 없으면 함수 호출에서 null을 반환합니다. 빈 결과 집합을 반환하는 문과 반대로 결과 집합을 반환하지 않는 문에서 이러한 함수 중 하나를 호출하면 false가 반환됩니다.
sqlsrv_fetch, sqlsrv_fetch_array 또는 sqlsrv_fetch_object를 사용할 경우 이러한 함수에 대한 다음 호출을 가능하게 하려면 먼저 각 데이터 행을 처리하는 코드를 포함시켜야 합니다. 인출된 각 행은 이러한 함수 중 하나에 대한 다음 호출이 이루어지면 더 이상 사용할 수 없게 됩니다.
이 항목에서는 두 가지 예제를 제공합니다. 첫 번째 예제에서는 단순 쿼리가 여러 번 실행될 때 결과 집합이 비어 있는지 확인합니다. 두 번째 예제에서는 저장 프로시저에서 반환된 결과 집합이 비어 있는지 확인합니다.
예
다음 예제에서는 sqlsrv_fetch_array를 사용하여 결과 집합이 비어 있는지 확인하는 방법을 보여 줍니다. 이 예제에서는 매번 다른 매개 변수 값을 사용하여 여러 번 쿼리를 실행합니다. "X"를 매개 변수 값으로 사용하여 쿼리를 두 번째로 실행하면 빈 결과 집합이 반환됩니다. 이 예제에서는 함수(ProcessRow)를 사용하여 결과가 들어 있는 결과 집합의 각 행을 처리합니다. 결과 집합이 비어 있으면 "The result set is empty"라는 메시지가 출력됩니다.
이 예제에서는 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");
if( !($conn = sqlsrv_connect( $serverName, $connectionInfo)))
{
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
/* Define the Tranasact-SQL query. */
$tsql = "SELECT EmailAddress FROM Person.Contact where LastName = ?";
/* Set up an array of parameter arrays. */
$param_arrays = array(
array("Jacobson"),
array("X"),
array("Akers")
);
/* Execute the query for each parameter array. */
foreach( $param_arrays as $params )
{
if( !($stmt = sqlsrv_query($conn, $tsql, $params)))
{
echo "Error in statement execution.\n";
die( print_r( sqlsrv_errors(), true));
}
echo "Results for LastName = $params[0]:\n";
/* Determine if there are results. If there are results, display
them. If there are no results, display an appropriate message.
If an error occured, display the error message.*/
$row = sqlsrv_fetch_array( $stmt );
if( $row )
{
/* Process each row of the result set and retrieve the next
row.*/
do
{
ProcessRow( $row );
$row = sqlsrv_fetch_array( $stmt );
} while( $row );
}
elseif( is_null($row))
{
echo "The result set is empty.\n";
}
elseif( $row === false )
{
die(print_r( sqlsrv_errors(), true ));
}
echo "----------------\n";
}
/* Free statement and connection resources. */
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
/* Function for processing a row of data. */
function ProcessRow( $row )
{
echo $row[0]."\n";
}
?>
이 예제의 목적은 빈 결과를 확인하는 데 있으므로 모든 함수 호출에서 오류를 확인하지는 않습니다. 오류 처리에 대한 자세한 내용은 오류 및 경고 처리를 참조하십시오.
다음 예제에서는 sqlsrv_fetch를 사용하여 결과 집합이 비어 있는지 확인하는 방법을 보여 줍니다. 이 예제에서는 매번 다른 매개 변수 값을 사용하여 여러 번 저장 프로시저를 실행합니다. 이 저장 프로시저에서는 판매 주문에서 품목(SalesOrderID)을 삭제하고, 해당 제품 ID의 재고 품목을 업데이트한 다음 판매 주문에서 남아 있는 품목을 반환합니다. "121293"을 매개 변수 값으로 사용하여 쿼리를 두 번째로 실행하면 한 품목만 주문하는 것에 해당됩니다. 저장 프로시저에서는 이 품목을 삭제하지만, 나머지 품목을 반환하도록 쿼리를 실행하면 결과 집합이 비어 있습니다. 이 예제에서는 함수(ProcessRow)를 사용하여 결과가 들어 있는 결과 집합의 각 행을 처리합니다. 결과 집합이 비어 있으면 "The result set is empty"라는 메시지가 출력됩니다.
이 예제에서는 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('UpdateInventory', 'P') IS NOT NULL
DROP PROCEDURE UpdateInventory";
$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 UpdateInventory
@SalesOrderDetailID int
AS
BEGIN
--Get the SalesOrderID, ProductID, and Quantity
DECLARE @SalesOrderID int;
DECLARE @ProductID int;
DECLARE @OrderQty int;
SELECT @SalesOrderID = SalesOrderID,
@ProductID = ProductID,
@OrderQty = OrderQty
FROM Sales.SalesOrderDetail
WHERE SalesOrderDetailID = @SalesOrderDetailID;
--Update Inventory
UPDATE Production.ProductInventory
SET Quantity = Quantity + @OrderQty
WHERE ProductID = @ProductID;
--Delete the OrderDetail
DELETE FROM Sales.SalesOrderDetail
WHERE SalesOrderDetailID = @SalesOrderDetailID;
--Get remaining products for SalesOrderID
SELECT SalesOrderID,
SalesOrderDetailID,
ProductID,
OrderQty
FROM Sales.SalesOrderDetail
WHERE SalesOrderID = @SalesOrderID;
END";
$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 UpdateInventory(?)}";
/* Define an array of parameter arrays. */
$param_arrays = array(
array(16434),
array(121293)
);
/* Execute the query for each parameter array. */
foreach($param_arrays as $params)
{
$stmt = sqlsrv_query( $conn, $tsql_callSP, $params);
if( $stmt === false)
{
echo "Error in executing statement.\n";
die( print_r( sqlsrv_errors(), true));
}
/* The first SELECT statement in the stored procedure only sets
the parameter values. It does not return a result set.*/
/* Display the rows affected by the UPDATE statement in the stored
procedure and move to the next result. */
echo "Rows updated: ".sqlsrv_rows_affected( $stmt )."\n";
sqlsrv_next_result($stmt);
/* Display the rows affected by the DELETE statement in the stored
procedure and move to the next result. */
echo "Rows deleted: ".sqlsrv_rows_affected( $stmt )."\n";
sqlsrv_next_result( $stmt );
/* Determine if there are results returned by the SELECT statement
of the stored procedure. If there are results, display them.
If there are no results, display an appropriate message. */
$row = sqlsrv_fetch( $stmt );
if( $row )
{
do
{
ProcessRow( $stmt );
$row = sqlsrv_fetch( $stmt );
}while( $row );
}
elseif( is_null( $row ))
{
echo "The result set is empty.\n";
}
elseif( $row === false )
{
die( print_r( sqlsrv_errors(), true));
}
echo "-------------------\n";
}
/* Free statement and connection resources. */
sqlsrv_free_stmt( $stmt1 );
sqlsrv_free_stmt( $stmt2 );
sqlsrv_free_stmt( $stmt );
sqlsrv_close( $conn );
function ProcessRow( $stmt )
{
echo "SalesOrderID: ".sqlsrv_get_field($stmt, 0)."\n";
echo "SalesOrderDetailID: ".sqlsrv_get_field($stmt, 1)."\n";
echo "ProductID: ".sqlsrv_get_field($stmt, 2)."\n";
echo "OrderQty: ".sqlsrv_get_field($stmt, 3)."\n\n";
}
?>
이 예제의 목적은 빈 결과를 확인하는 데 있으므로 모든 함수 호출에서 오류를 확인하지는 않습니다. 오류 처리에 대한 자세한 내용은 오류 및 경고 처리를 참조하십시오.
참고 항목
개념
데이터 검색 함수 비교
설명서에 포함된 코드 예제 정보
관련 자료
데이터 검색
데이터 업데이트(SQL Server Driver for PHP)
API 참조(SQL Server Driver for PHP)