Calling MSSQL stored proc from php - php

We have been stumped with this all morning.
I have an MSSQL stored proc which processes some records. Each record generates an email with dynamic content, and this is populated from another stored proc.
So the first stored proc has a cursor, and each row is processed resulting in a call to another stored proc, which itself has a cursor to loop through. The first stored proc has no output parameters or returned values, etc, while the second uses output parameters to return fields to the first proc.
This works fine from Datagrip.
Calling this from php using PDO (or using other drivers) it fails to run fully. It would produce a small batch of records then stop (tends to be either 5, 9, 13 or 45 - has changed as we have experimented with difference solutions).
We have managed to get it to run now using PDOStatement::nextRowset . We use a query of the first stored proc and then using while ( $stmt->nextRowset() ) ; to loop through the (non existent / unwanted) row sets.
This works. But as the first stored proc isn't returning anything (just that pdo seems to want to process some kind of internal result set) this seems very dirty and inefficient.
Is there an alternative? Possibly a parameter to pass to pdo, or a setting within the stored proc?
Below there is some simplified code to show how things interact.
PHP calling script.
<?php
$emailRepository = new EmailRepository(hostname, port, dbname, username, password);
$ret = $emailRepository->sendRenewalEmails();
class EmailRepository
{
public function __construct($hostname, $port, $dbname, $username, $password)
{
$this->hostname = $hostname;
$this->port = $port;
$this->dbname = $dbname;
$this->username = $username;
$this->password = $password;
$this->connect();
}
private function connect()
{
try {
$this->db = new PDO ("sqlsrv:Server=$this->hostname,$this->port;Database=$this->dbname", $this->username, $this->password);
$this->db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch (PDOException $e) {
var_dump("Failed to get DB handle: " . $e->getMessage());
}
}
public function sendRenewalEmails()
{
try {
$stmt = $this->db->prepare("EXEC membership_queue_renewal_emails");
$stmt->execute();
do {
echo '>';
} while($stmt->nextRowset());
return true;
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
First stored proc (heavily cut down)
CREATE PROCEDURE [dbo].[queue_renewal_emails]
AS
BEGIN
DECLARE #curr_member_cursor CURSOR;
DECLARE #curr_club_cursor CURSOR;
DECLARE #g_personid INT;
DECLARE #g_emailTemplateId INT;
DECLARE #g_email_subject VARCHAR(200);
DECLARE #g_email_html VARCHAR(max);
DECLARE #g_email_plain VARCHAR(max);
DECLARE #g_personEmail VARCHAR(128);
SET #curr_club_cursor = CURSOR
LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR
SELECT DISTINCT
bgemailTemplate.bgemte_name,
bgemailTemplate.bgemte_emailtemplateid,
vpersonpe.pers_emailaddress,
vpersonpe.pers_personId,
FROM company WITH(NOLOCK)
INNER JOIN complink WITH(NOLOCK) ON complink.clli_companyid = complink.Comp_CompanyId
AND complink.clli_Deleted is null
INNER JOIN vpersonpe WITH(NOLOCK) ON vpersonpe.pers_personId = complink.clli_personId
INNER JOIN bgemailTemplate WITH(NOLOCK) ON bgemailTemplate.bgemte_Deleted IS NULL
WHERE vPersonPE.pers_deleted IS NULL
AND company.comp_deleted IS NULL
AND vPersonPE.pers_parentid IS NULL
AND vpersonpe.pers_status NOT IN ('Cancelled','Expired','Suspended','Awaiting Approval','Declined','On hold','Revoked','Expelled');
-- loop through each course
OPEN #curr_club_cursor;
FETCH NEXT FROM #curr_club_cursor INTO #g_email_subject, #g_emailTemplateId, #g_personEmail, #g_personid;
WHILE ##fetch_status = 0
BEGIN
EXEC dbo.populateEmail #g_emailtemplateid /* Email template id */,
#g_email_plain OUTPUT /* Plain text email to have the placeholders replaced */,
#g_email_subject OUTPUT,
#g_personid ;
FETCH NEXT FROM #curr_club_cursor INTO #g_email_subject, #g_emailTemplateId, #g_personEmail, #g_personid;
END
CLOSE #curr_club_cursor
DEALLOCATE #curr_club_cursor
END
go
Second stored proc (heavily cut down).
CREATE PROCEDURE [dbo].[populateEmail]
#p_emailtemplateid INT,
#p_email_text VARCHAR(max) OUTPUT,
#p_email_subject VARCHAR(200) OUTPUT,
#p_person_id INT
AS
BEGIN
SET NOCOUNT ON;
-- CURSORs
DECLARE #curr_field_cursor CURSOR;
DECLARE #g_email_plain VARCHAR(MAX) = '';
DECLARE #g_email_subject VARCHAR(200) = '';
DECLARE #g_emte_emailtemplateid INT;
DECLARE #g_EmailPlaceholderId INT;
DECLARE #g_place_holder VARCHAR(128);
DECLARE #g_source_column VARCHAR(128);
DECLARE #g_prev_source_query_num INT;
DECLARE #g_source_query_num INT;
-- Variables to read results into from each query
DECLARE #g_q11_comp_name VARCHAR(180);
DECLARE #g_q11_comp_website VARCHAR(300);
DECLARE #g_q11_comp_pers_salutation VARCHAR(30);
DECLARE #g_q11_comp_pers_firstname VARCHAR(90);
DECLARE #g_q11_comp_pers_lastname VARCHAR(120);
-- Start processing
SET #p_email_text = '';
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SET #curr_field_cursor = CURSOR
LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR
SELECT a.emte_emailtemplateid,
b.emtl_EmailPlaceholderId,
c.empl_PlaceHolder,
c.empl_SourceQueryNum,
c.empl_SourceColumn,
a.emte_plaintextemail,
a.emte_subject
FROM EmailTemplate a with (nolock)
LEFT OUTER JOIN EmailTemplateLink b with (nolock)
ON a.emte_emailtemplateid = b.emtl_EmailTemplateId
LEFT OUTER JOIN EmailPlaceholder c with (nolock)
ON b.emtl_EmailPlaceholderId = c.empl_EmailPlaceholderID
WHERE a.emte_emailtemplateid = #p_emailtemplateid
ORDER BY c.empl_SourceQueryNum;
-- Loop through each required place holder for the passed email template.
SET #g_prev_source_query_num = 0;
OPEN #curr_field_cursor
FETCH NEXT FROM #curr_field_cursor INTO #g_emte_emailtemplateid, #g_EmailPlaceholderId, #g_place_holder, #g_source_query_num, #g_source_column, #g_email_plain, #g_email_subject;
WHILE ##fetch_status = 0
BEGIN
IF #g_prev_source_query_num = 0
BEGIN
SET #p_email_text = #g_email_plain;
SET #p_email_subject = #g_email_subject;
END;
IF #g_source_query_num = 11
BEGIN
IF #g_prev_source_query_num != #g_source_query_num
BEGIN
SELECT #g_q11_comp_name = comp_name,
#g_q11_comp_website = comp_website,
#g_q11_comp_pers_salutation = Pers_Salutation,
#g_q11_comp_pers_firstname = pers_firstname,
#g_q11_comp_pers_lastname = pers_lastname
FROM company with (nolock)
LEFT OUTER JOIN vPerson with (nolock) ON company.Comp_PrimaryPersonId = vPerson.Pers_PersonId
LEFT OUTER JOIN address with (nolock) ON company.Comp_PrimaryAddressId = address.Addr_AddressId
WHERE company.Comp_CompanyId = #p_person_id;
END;
IF #g_source_column = 'comp_name'
BEGIN
SET #p_email_text = REPLACE(#p_email_text, #g_place_holder, COALESCE(#g_q11_comp_name, ''));
SET #p_email_subject = REPLACE(#p_email_subject, #g_place_holder, COALESCE(#g_q11_comp_name, ''));
END;
ELSE IF #g_source_column = 'comp_website'
BEGIN
SET #p_email_text = REPLACE(#p_email_text, #g_place_holder, COALESCE(#g_q11_comp_website, ''));
SET #p_email_subject = REPLACE(#p_email_subject, #g_place_holder, COALESCE(#g_q11_comp_website, ''));
END;
ELSE IF #g_source_column = 'comp_primary_person_firstname'
BEGIN
SET #p_email_text = REPLACE(#p_email_text, #g_place_holder, COALESCE(#g_q11_comp_pers_salutation, ''));
SET #p_email_subject = REPLACE(#p_email_subject, #g_place_holder, COALESCE(#g_q11_comp_pers_salutation, ''));
END;
ELSE IF #g_source_column = 'comp_primary_person_salutation'
BEGIN
SET #p_email_text = REPLACE(#p_email_text, #g_place_holder, COALESCE(#g_q11_comp_pers_firstname, ''));
SET #p_email_subject = REPLACE(#p_email_subject, #g_place_holder, COALESCE(#g_q11_comp_pers_firstname, ''));
END;
ELSE IF #g_source_column = 'comp_primary_person_lastname'
BEGIN
SET #p_email_text = REPLACE(#p_email_text, #g_place_holder, COALESCE(#g_q11_comp_pers_lastname, ''));
SET #p_email_subject = REPLACE(#p_email_subject, #g_place_holder, COALESCE(#g_q11_comp_pers_lastname, ''));
END;
END;
SET #g_prev_source_query_num = #g_source_query_num;
FETCH NEXT FROM #curr_field_cursor INTO #g_emte_emailtemplateid, #g_EmailPlaceholderId, #g_place_holder, #g_source_query_num, #g_source_column, #g_email_plain, #g_email_subject;
END;
CLOSE #curr_field_cursor
DEALLOCATE #curr_field_cursor
END
go

as the first stored proc isn't returning anything ... is there an alternative to while ( $stmt->nextRowset() ) ;
I'ts probably the rowcount messages causing the client to see empty rowsets. Add SET NOCOUNT ON as the first line of each stored procedure.

Related

Is it possible to pass multiple input values in stored procedure parameter?

I am working on a fantasy baseball optimizer and I have a stored procedure where when the user selects players it will return the best possible player, but the problem is, the sp only does it for one player at a time. I wanted to know if there was a way the sp could do it for at most nine players at one time.
Visual Reference
Here's the code for the stored procedure:
DELIMITER $$
CREATE DEFINER=`u998875936_chri`#`%` PROCEDURE `Optimizer9`(
PlayerName varchar(30),
PlayerPosition varchar(2),
PlayerSalary int,
PlayerFPPG Numeric (20,17),
CapRemaining int,
OUT ReturnPlayerName varchar(30),
OUT ReturnCap int
)
BEGIN
Declare Count int;
Declare lclSal int;
Declare lclPlayerName varchar(30);
Declare lclReturnPlayerName varchar(30);
Declare lclCap int;
Set lclPlayerName='';
Set lclReturnPlayerName='';
Set lclSal=0;
Set lclCap = CapRemaining;
Set Count=0;
create temporary Table IF NOT EXISTS TempPlayer9(
Player varchar(30),
Pos varchar(2),
Sal int,
Points Numeric (20,17)
);
Insert into TempPlayer9 (Player,Pos,Sal,Points)
SELECT Nickname
,Position
,Salary
,FPPG
FROM playerList
WHERE POSITION = PlayerPosition
and FPPG > PlayerFPPG
order by FPPG DESC;
Set Count=(Select Count(*) from TempPlayer9);
While Count > 0
DO
Set lclPlayerName=(Select Player from TempPlayer9 LIMIT 1);
Set lclSal=(Select Sal from TempPlayer9 LIMIT 1);
IF (lclsal- PlayerSalary) < lclCap
THEN
Set lclCap = lclCap - (lclSal- PlayerSalary);
Set lclReturnPlayerName = lclPlayerName;
Set Count=0;
DELETE from TempPlayer9 Where Player = lclPlayerName;
Set Count=Count-1 ;
END IF;
END WHILE;
Set ReturnPlayerName = lclReturnPlayerName;
Set ReturnCap = lclCap;
END$$
DELIMITER ;
PHP Code:
<?php
$remain=35000;
$player= $_POST['player'];
$pos= $_POST['pos'];
$sal= $_POST['sal'];
$points= $_POST['fppg'];
$cap= $remain-$sal;
$sql = $mysqli->query("call Optimizer11('$player', '$pos','$sal' , '$points', '$cap', #ReturnPlayerName, #ReturnCap)");
$results = $mysqli->query ("select #ReturnPlayerName as Player,#ReturnCap AS SalRemaining");
$rows = mysqli_fetch_array($results);
print_r($rows);
?>

String Value in a concat procedure [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I know my questions sounds silly , but i'm not able to run my code because of that problem , all my procedure is correct , my only one problem is that i'm not able to use syntax that contains a string which is :
SET #query = CONCAT(#query, ' WHERE i.active=T');
I tried to use + between the apostrophe and . , however in all cases not working...
here is the full procedure
CREATE PROCEDURE stocktakess()
BEGIN
DECLARE wid INT;
DECLARE wname VARCHAR(20);
DECLARE query TEXT DEFAULT '';
DECLARE finished INT DEFAULT 0;
DECLARE whouse_cursor CURSOR FOR SELECT Id, name FROM warehouse WHERE Id IN (1,2,3,5,8);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
OPEN whouse_cursor;
SET #query = 'SELECT i.code,i.code2,i.description';
get_whouse: LOOP
FETCH whouse_cursor INTO wid, wname;
IF finished = 1 THEN
LEAVE get_whouse;
END IF;
SET #query = CONCAT(#query, ', SUM(CASE WHEN m.warehouseID=', wid, ' THEN COALESCE(m.qtyin, 0) - COALESCE(m.qtyout, 0) ELSE 0 END) AS `', wname, '`');
END LOOP get_whouse;
SET #query = CONCAT(#query, ' FROM items i LEFT JOIN itemmovement m ON m.itemid = i.Id');
SET #query = CONCAT(#query, ' WHERE i.active=T');
SET #query = CONCAT(#query, ' GROUP BY i.Id');
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
CREATE PROCEDURE stocktakess()
BEGIN
DECLARE wid INT;
DECLARE wname VARCHAR(20);
DECLARE query TEXT DEFAULT '';
DECLARE finished INT DEFAULT 0;
DECLARE whouse_cursor CURSOR FOR SELECT Id, name FROM warehouse WHERE Id IN (1,2,3,5,8);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
OPEN whouse_cursor;
SET #query = 'SELECT i.code,i.code2,i.description';
get_whouse: LOOP
FETCH whouse_cursor INTO wid, wname;
IF finished = 1 THEN
LEAVE get_whouse;
END IF;
SET #query = CONCAT(#query, ', SUM(CASE WHEN m.warehouseID=', wid, ' THEN COALESCE(m.qtyin, 0) - COALESCE(m.qtyout, 0) ELSE 0 END) AS `', wname, '`');
END LOOP get_whouse;
SET #query = CONCAT(#query, ' FROM items i LEFT JOIN itemmovement m ON m.itemid = i.Id');
SET #query = CONCAT(#query, ' WHERE i.active=\'T\'');
SET #query = CONCAT(#query, ' GROUP BY i.Id');
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END

Calling from PHP Stored Procedure with Cursor and Union SQL Doesn't Show All Data

I Create a stored procedure that execute perfectly in MYSQL but when I call it from PHP it only show the data that correspond to the first data of the cursor.
Here is how I call the stored procedure :
$sql = mysqli_query($db, "CALL MySP('".$ec4."')");
Here is how I retrieve the data:
while ($ligne = mysqli_fetch_array($sql))
Thank you
Stored procedure data
php calling
while ($ligne = mysqli_fetch_array($sql)) {
echo '</br>';
echo '</br>'.$ligne["Agences"].'</br>';
echo '</br>'.$ligne["date_op"].'</br>';
echo '</br>'.$ligne["arrivee"].'</br>';
}
Here is my Stored Procedure :
DELIMITER $
CREATE PROCEDURE `MySP`( date_op VARCHAR(10) )
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE ville_agence VARCHAR(50);
DECLARE cursor_i CURSOR FOR SELECT ville FROM villes;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cursor_i;
read_loop: LOOP
FETCH cursor_i INTO ville_agence;
IF done THEN
LEAVE read_loop;
END IF;
SELECT
Agences,
date_op,
(select Villes from grille a where a.Nom = b.Nom_de_Depart and a.`Type` ='A' LIMIT 1) as arrivee
FROM
grille b
where
b.`Type` = 'T'
and upper(Agences) in (ville_agence)
UNION
SELECT
Agences,
date_op,
(select Agences from grille a where a.Code = b.Code and a.`Type` = 'D' LIMIT 1) as arrivee
FROM
grille b
where b.`Type` = 'A'
and upper(Agences) in (ville_agence);
END LOOP;
CLOSE cursor_i;
END

MySQL Stored Procedure Empty in PHP works in PHPMyAdmin

I have the following stored procedure. It works fine in phpMyAdmin, but when I try to run it using PHP PDO library I get no errors, just an empty array.
CREATE DEFINER=`root`#`localhost`
PROCEDURE `get_gauge_values`(IN `maxdate` TIMESTAMP,
IN `dashboard_id` INT)
begin
DECLARE finished BOOLEAN;
DECLARE line_timestamp TIMESTAMP;
DECLARE line_tagid INT;
DECLARE line_name VARCHAR(50);
DECLARE line_value VARCHAR(50);
DECLARE cid CURSOR FOR
SELECT Max(hd.timestamp),
hd.tag_id
FROM dashboard_to_dashboard_lines ddl
JOIN dashboard_lines dl
ON dl.line_id = ddl.dashboard_line_id
JOIN historical_data hd
ON hd.tag_id = dl.gauge_tag_id
WHERE hd.timestamp <= maxdate
AND ( dashboard_id = 0
OR ddl.dashboard_id = dashboard_id )
GROUP BY 2;
DECLARE CONTINUE handler
FOR NOT found
SET finished=TRUE;
SET finished=FALSE;
DROP TABLE IF EXISTS gauge_values_temp;
CREATE TABLE gauge_values_temp
(
name VARCHAR(255),
value VARCHAR(50)
);
open cid;
START_LOOP:
LOOP
FETCH cid INTO line_timestamp, line_tagid;
IF finished <> false THEN
LEAVE start_loop;
ELSE
INSERT INTO gauge_values_temp
(name,
value)
SELECT ol.name,
hd.value
FROM dashboard_lines dl
JOIN operation_lines ol
ON ol.line_id = dl.line_id
JOIN historical_data hd
ON hd.tag_id = dl.gauge_tag_id
WHERE dl.gauge_tag_id = line_tagid
AND hd.timestamp = line_timestamp;
end IF;
end LOOP;
close cid;
SELECT *
FROM gauge_values_temp;
end
The code that I use in PHP for trying to pull data back is the following:
try {
$sql = "CALL get_gauge_values('2015-12-28 09:00:00','1')";
$q = $link->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
} catch (PDOException $pe) {
die("Error occurred:" . $pe->getMessage());
}
while ($r = $q->fetch()) {
echo 'Row returned<br />';
}
exit;
I'm confused as to why it returns the result set in phpMyAdmin but running it with the PHP code below in a browser returns 0 rows. All I get when I print_r($q) is Array( )...

Returning values from stored procedure using TSQL and PHP

Is it possible to get data returned from a Stored procedure in PHP using SQLSRV connecting to a windows server DB. At the moment, the code I have commits the query succesfully but doesn't return anything. The loop where the rows output does not run even once (ie the object is empty)
Here's the PHP
/* Set up and execute the first query. */
$sql1 = "
USE CRDCMS2PublicDevelopment
EXEC SearchForXML6b
#SessionID = 973543,
#LineID = 892245,
#SortOrder = 'YearPublished DESC, SortTitle ASC',
#PageNumber = 1,
#RecordsPerPage = 20
";
$params1 = array( $orderId, $qty, $productId );
$stmt1 = sqlsrv_query( $conn, $sql1/*, $params1*/ );
/* Display the value of the output parameters. */
while ( $obj = sqlsrv_fetch_object( $stmt1 ) ) {
//SET PARAMETERS - SET TERMS
echo 'loop';
echo $obj->listingXML;
}
/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 ) {
sqlsrv_commit( $conn );
echo "Transaction committed.<br />";
} else {
sqlsrv_rollback( $conn );
echo "Transaction rolled back.<br />";
}
Here's the Stored procedure
USE [ my db name ]
GO
/****** Object: StoredProcedure [dbo].[ SPROC name ] Script Date: 12/08/2013 14:45:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[ SPROC name ]
#DatabaseID int = 1,
#PageNumber int = 1,
#RecordsPerPage int = 20,
#SessionID int = 0,
#LineID int = 0,
#SearchFor nvarchar(max) = '',
#UserID int = 0,
#SortOrder nvarchar(max) = 'YearPublished DESC, SortTitle ASC',
#Published int = 3, -- -1=all, 0=not published, 1=prov, 2=full, 3=all published
#SearchXML nvarchar(max) = '', -- xml representation of advanced search
#ShowSelected int = 0,
#IsWebSearch int = 0
AS
BEGIN
SET NOCOUNT ON;
--SET #recordsPerPage = 50
-- ----------------------------------------------------------------------------------------------
-- don't allow a null page number or recs per page
-- ----------------------------------------------------------------------------------------------
if #PageNumber is null
SET #PageNumber = 1
if #RecordsPerPage is null
SET #RecordsPerPage = 20
-- ----------------------------------------------------------------------------------------------
-- Set up the header of the SQL to run
-- ----------------------------------------------------------------------------------------------
DECLARE #sql nvarchar(max)
set #sql = '
DECLARE #sql nvarchar(max)
DECLARE #startRow int
DECLARE #endRow int
SET #startRow = '+STR(((#PageNumber-1) * #RecordsPerPage)) + '
SET #endRow = '+STR(((#PageNumber) * #RecordsPerPage)+1) + '
DECLARE #total int
DECLARE #t TABLE (RowNumber int IDENTITY, AccessionNumber bigint not null, SortTitle nvarchar(450), YearPublished int, DatabaseID int, RecordTypeID int, Selected int NULL, Source nvarchar(450))'
SET #sql = #sql + '
DECLARE #hits varchar(max)
SELECT #hits = Hits from UserHitTemp where LineID = ' + LTRIM(RTRIM(STR(#lineID))) + '
insert into #t ( AccessionNumber, SortTitle , YearPublished , DatabaseID , RecordTypeID , Source)
SELECT C.AccessionNumber, SortTitle, YearPublished, DatabaseID, RecordTypeID, ISNULL((select top 1 FieldText from SearchField where AccessionNumber = C.accessionNumber and SearchTag = ''SO''),'''') as Source
FROM dbo.SplitAccessionList(#hits) H
JOIN CRDDocument C on C.AccessionNumber = H.AccessionNumber ORDER BY ' + #SortOrder
SET #sql = #sql + '
set #total = ##ROWCOUNT
DECLARE #xml XML
SET #xml = (
SELECT TOP 1 #total as "#RecordCount",
0 as "#SelectedCount",
'+LTRIM(RTRIM(STR(#SessionID)))+' as "#SearchSessionID",
'+LTRIM(RTRIM(STR(#PageNumber)))+' as "#PageNumber",
'+LTRIM(RTRIM(STR(#RecordsPerPage)))+' as "#RecordsPerPage",
'+LTRIM(RTRIM(STR(#LineID)))+' as "#LineID",
''advanced)'' as "#SearchType",
( SELECT dbo.GetRecordForListingXML(AccessionNumber, RowNumber,ISNULL(Selected,0))
FROM #t T
WHERE T.RowNumber > #startRow and T.RowNumber < #endRow
FOR XML PATH(''''), ELEMENTS, TYPE
)
FOR XML PATH(''listing''), ELEMENTS
)
SELECT #XML as listingXML'
-- ----------------------------------------------------------------------------------------------
-- Run the SQL to extract the results as XML
-- ----------------------------------------------------------------------------------------------
PRINT #sql
EXEC sp_executesql #sql
END
Please note: if i copy and paste the exact sql used in the php ($sql1) it returns one row correctly in SQL server management studio. I think what I'm trying can be done, is this the right way?
Thanks.
It looks like all the stored-procedure is doing is building the variable #sql.
Try adding this at the bottom of the stored-procedure:
EXEC #sql

Categories