I have a stored procedure that returns multiple result sets from an MSSQL database. The problem I'm having is looping through each result set. It seems Yii is not advancing to the next result set to iterate through the rows. Here is an example:
RESULT 1:
TOTAL
-----
999
RESULT 2:
ID |NAME
---|----
0 | Jon
1 | Bob
2 | Sarah
3 | Pete
And here's my attempt at making this work in Yii.
//create the call to stored proc
$command=parent::$db->createCommand("exec sp_showUsers");
//run the query
$dataReader = $command->query();
//For the current object assign the row to a variable
while (($row = $dataReader->read()) !== false){
//if the row has a total column
if(isset($row['total'])){
$total = $row['total'];
}
}
//Test if there is another result
$usersExist = $dataReader->nextResult();
//$dataReader->next(); - REMOVED AS NOT NEEDED
if($usersExist){
$userTable = array();
$i = 0;
while (($userRow = $dataReader->read())!== false){
//add each row to a temporary array
$userTable[$i] = $userRow['id'];
$i++;
}
}
...
This doesn't seem to loop through the second result set even though the ->next()
method has been called? Any help would be very appreciated! Thanks.
P.s The stored procedure does work and I can loop through the results using ordinary PHP and the sqlsrv_next_result()
method.
In the code, why
$dataReader->nextResult()
will return a CDbDataReader
Object.
So, you are using $dataReader->next();
this will move the pointer of first result only. You have to move the pointer returned by nextResult()
call.
I think,
$dataReader=$dataReader->next();
will solve the problem
I found the answer. It was the way we were binding the params to our stored procedure that was messing up our results. We don't need the $dataReader->next(); at all. so all is working ok with the code above. I hope this helps someone out who is using SQL server stored procedures with Yii. :) And just in case anyone needs the stored procedure call example:
$command=parent::$db->createCommand("exec sp_showUsers :pageNumber, :pageSize, :sortOrder, :viewAll");
$command->bindParam(":pageSize", $pageSize, PDO::PARAM_INT);
$command->bindParam(":pageNumber", $pageNumber, PDO::PARAM_INT);
$command->bindParam(":sortOrder", $sortOrder, PDO::PARAM_STR);
$command->bindParam(":viewAll", $viewAll, PDO::PARAM_BOOL);
$dataReader = $command->query();