开发者

Retrieve data returned by a Stored Procedure: Php & MS SQL SERVER

This question relates to:

PHP Version 5.3.6

Microsoft Drivers for PHP for SQL Server

I am trying to properly retrieve data from a stored procedure.

This question assumes the existence of the following stored procedure:

CREATE PROCEDURE test_procedure
AS
     BEGIN
           SET NOCOUNT ON
           --A bunch of SQL statements
           --More SQL statements
           SELECT 'Doctor Who Rules!'
     END

I've tried the following code which runs through all of my commands but does not return the data from the final SELECT.

$sql = "EXEC test_procedure;";
$result = sqlsrv_query($conn,$sql);
$next_result = sqlsrv_next_result($result); // returns a boolean
$row = sqlsrv_fetch_array($result);

Using sqlsrv_execute does not work with the above c开发者_运维百科ode either.

How can I return the data geneated by the stored procedure above via PHP?

Thank you.

Addendum #1 (Classic ASP Counterpart)

sqlCMD = "EXEC test_procedure;"
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open _ConnectionString_Variable_
Set rs = conn.Execute(sqlCMD)

I would get back a recordset with one row that has one field with the data "Doctor Who Rules!"


I just hit the same problem a few minutes ago, and this thread pointed me towards a working solution (I'm not sure that it is a "right"solution, but it works).

Actually, the problem was not being caused by "SET NOCOUNT ON". In my case, it was a couple of PRINT statements that were left there after debugging.

Looks like any output from the SP other than the actual recordset, causes the problem.


I figured out the problem.

The PHP code in my example will work properly if SET NOCOUNT ON is ommited from the Stored Procedure. With SET NOCOUNT ON in the procedure, there is no data stream back to PHP and thus, the results of the last SELECT never makes it back.

Therfore, this Stored procedure...

CREATE PROCEDURE test_procedure
     @foo varchar(25)
AS
     BEGIN
          --A bunch of SQL statements
          --More SQL statements
          SELECT @foo
END

...will work perfectly with this PHP...

$sql = "EXEC test_procedure 'Dr. Who Rules!';";
$result = sqlsrv_query($conn,$sql);
$next_result = sqlsrv_next_result($result);
$row = sqlsrv_fetch_array($result);

You will end up with a recordset with the string "Doctor Who Rules!"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜