简体   繁体   中英

Using MSSQL STUFF in query with PHP

So first let me explain what I'm trying to do, then how I'm doing it, and then what the problem is. I'm trying to create a mssql query to read invoices from a database. Each invoice is essentially a compilation of individual charges grouped together by an invoice ID. The catch is that different charges could come from different containers (charges are associated with containers). What I need to do is group the charges by invoice ID and concatenate the container names for all the charges in an invoice, with some delimiter like "|". I have created a temporary table @t that holds all the charges and container names needed to generate an invoice. After looking online for quite a while, I found the STUFF command which appears to do what I want (appears, and does). So here is the SQL for my query:

select invoice_id, [Total Paid] RefNumCount,PayCount, MIN([rowNumber]) as rowNumber,     Vendor, Due, [Invoice Number], Company, MAX(Location) as Location,
 SUM([Funded Amount]) as [Funded Amount], 
 [Company ID], [Invoice ID], provider_reference_number, reconcile_date, all_providers
, STUFF(
        (
        select '|' + t1.[Container Name]
        from @t t1
        where t1.[Invoice Number] = t.[Invoice Number]
        order by t1.[Container Name]
        for XML PATH(''), TYPE
        ).value('.', 'nvarchar(100)')
        ,1,1,''
     ) as [Container Name] 

from @t t
group by invoice_id, [Total Paid], RefNumCount, PayCount, Vendor, Due, [Invoice Number], Company, 
    [Company ID], [Invoice ID], provider_reference_number, reconcile_date, all_providers

When I run this is SQL Server Management Studio 2008, it runs just fine. However, when I use this code in my PHP application, the query does not work and ultimately I get a fatal error by trying to read an empty result set. Does anybody know why this problem is happening? Or if there is another way to concatenate strings?

The following is the PHP Code segment used to call the query

           try{
                $q = cms_database::instance();
                 $result = $q->query($sql_statement);        
                 if (!$result) {
                       throw new Exception("Database Error [{$q->errno}] {$q->error}");
                  } 

                $invoices = array();
                while($row=$result->fetch_assoc()) {
                    $invoiceX = array();
                    $invoiceX["rowNum"]     = $row["rowNumber"];
                    $invoiceX["Vendor"]     = $row["Vendor"];
                    $invoiceX["Due"]        = $row["Due"];
                    $invoiceX["Acct"]       = $row["Container Name"];//$row["Account Number"];
                    $invoiceX["container_id"]=$row["container_id"];
                    $invoiceX["provider_id"] =$row["provider_id"];
                    $invoiceX["Invoice"]    = $row["Invoice Number"];
                    $invoiceX["Location"]   = $row["Company"];
                    $invoiceX["FundedAmt"]  = $row["Funded Amount"];
                    $invoiceX["InvoiceID"]  = $row["Invoice ID"];
                    $invoiceX["Notes"]      = $row["Notes"];
                    //merge the notes with notes from payment history that matches the invoiceid


                    $invoices[] = $invoiceX;
                }

                //filter out invoices with all reference numbers accounted for and remaining to be paid is $0.00



                $returnPackage["data"] = $invoices;
                //print $result;
            } catch (Exception $e){
                $returnPackage["success"]=0;
                $returnPackage["message"]=$e.message;

            }

And the error I'm getting is: "
: Call to a member function fetch_assoc() on a non-object in on line :在第行的的非对象上调用成员函数fetch_assoc()
"

Line 116 is the line of code

while($row=$result->fetch_assoc()) {

Though this might come a little late, but try this SQL call instead.

select invoice_id, [Total Paid] RefNumCount,PayCount, MIN([rowNumber]) as rowNumber, 
       Vendor, Due, [Invoice Number], Company, MAX(Location) as Location,
       SUM([Funded Amount]) as [Funded Amount], [Company ID], [Invoice ID],
       provider_reference_number, reconcile_date, all_providers , 
       STUFF((select '|' + t1.[Container Name]
              from @t t1
              where t1.[Invoice Number] = t.[Invoice Number]
              order by t1.[Container Name]
              for XML PATH('')),1,1,'') as [Container Name] 
from @t t
group by invoice_id, [Total Paid], RefNumCount, PayCount, Vendor, Due, [Invoice Number], 
         Company, [Company ID], [Invoice ID], provider_reference_number, reconcile_date, 
         all_providers

The error occured when you added '|' at the select statement below which will strip away the xml tags, causing error when you use .value() trying to extract the data.

STUFF((select '|' + ... from ... for XML PATH(''), TYPE).value('.', 'nvarchar(100)'),1,1,'')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM