I have a stored procedure running in MS SQL 2008 R2 which runs fine in SQL Management Studio. However, if I run it from PHP it seems to stop execution before finishing. There is no error returned in SQL and no error returned in the PHP error log. The procedure simply writes to an error log a number of times using a second stored procedure. I have cut the code down to a simple loop to demonstrate reproducing the problem. This is the main stored procedure.
ALTER PROCEDURE [dbo].[usp_failure_test]
AS
DECLARE
@counter int,
@message nvarchar(100)
SET @counter = 0;
WHILE @counter < 100
BEGIN
SET @message = 'COUNT: ' + CAST(@counter AS nvarchar);
EXEC usp_log 0, 'TEST', @message;
SET @counter += 1;
END
EXEC usp_log 0, 'TEST', 'Finished';
This calls the procedure usp_log
ALTER PROCEDURE [dbo].[usp_log]
@engine_id int,
@type nvarchar(15),
@message text
AS
DECLARE
@last int,
@log_size int
INSERT INTO [dbo].[log] (engine_id, timestamp, type, message) VALUES (@engine_id, getdate(), @type, @message);
SET @log_size = CONVERT(int, (dbo.get_setting('log_size')))
SET @last = (SELECT TOP 1 id FROM log ORDER BY id DESC)
DELETE FROM log WHERE id < (@last - @log_size)
return
If I execute usp_failure test from SSMS it writes all of the expected log entries and then stops successfully. However, if I execute it from PHP (with the following code), it only reaches 52 and then stops without any clue as to why.
<?php
$servername = "localhost\sqlexpress";
$connectionInfo = array("UID" => "xxx", "PWD" => "xxx", "Database"=>"xxx", "ReturnDatesAsStrings"=>true, "CharacterSet" =>"UTF-8");
$conn = @sqlsrv_connect($servername, $connectionInfo);
$query = "usp_failure_test";
$params = array();
$result = sqlsrv_query($conn, $query, $params);
?>
I have tried adding in extra lines of code and this makes it fail after even fewer iterations. I have ensured that PHP has plenty of memory to work with and I’ve also checked the PHP and SQL logs to no avail. We’ve also used SQL profiler which did not show up any issues either.
Try using
SET NOCOUNT ONin your stored procedures. You are likely hitting a limit on the number of results that can be returned to PHP from the sql server PHP driver.