如何:偵測空白結果集
本主題將示範使用 SQL Server Driver for PHP 時,如何判斷結果集是否為空的。
注意
如果您正在使用 SQL Server Driver for PHP 1.1 版,就可以使用 sqlsrv_has_rows 來查看結果集是否具有資料列。
在 SQL Server Driver for PHP 1.1 版中,判斷陳述式的結果集是否為空,建議作法是針對此陳述式呼叫 sqlsrv_fetch、sqlsrv_fetch_array 或 sqlsrv_fetch_object 並檢視傳回值。如果使用中結果集不包含結果,函數呼叫會傳回 null。請注意,如果您針對沒有傳回結果集的陳述式 (而非傳回空白結果集的陳述式) 呼叫上述其中一個函數,它就會傳回 false。
當您使用 sqlsrv_fetch、sqlsrv_fetch_array 或 sqlsrv_fetch_object 時,必須先加入處理每個資料列的程式碼,然後再進行上述任何函數的後續呼叫。後續呼叫上述其中一個函數之後,將無法再使用已經提取的每個資料列。
本主題將提供兩種範例。第一個範例會在多次執行簡單查詢時,檢查是否有空的結果集。第二個範例會檢查預存程序是否傳回空的結果集。
範例
下列範例示範如何使用 sqlsrv_fetch_array 來判斷是否為空的結果集。範例會執行查詢多次,且每次都會使用不同的參數值。請注意,查詢的第二次執行 (使用 X 當做參數值) 傳回了空的結果集。範例使用函數 (ProcessRow) 來處理包含結果的結果集中的每一個資料列。如果結果集是空的,會列印下列訊息:「結果集是空的」。
此範例假設 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)、更新對應產品識別碼的庫存項目,然後傳回該銷售訂單剩餘的行項目。請注意,查詢的第二次執行 (使用 121293 當做參數值) 對應到只有一個行項目的訂單。預存程序會刪除此行項目,但是執行查詢以傳回剩餘的行項目時,此結果集會是空的。範例使用函數 (ProcessRow) 來處理包含結果的結果集中的每一個資料列。如果結果集是空的,會列印此訊息:「結果集是空的」。
此範例假設 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)