简体   繁体   中英

How do i get the `ResponseDescription` value in Microsoft Sql?

So the column i'm querying has an XML data that looks like this

<soap:Envelope xmlns:soap="http://google.com/">
    <soap:Body>
        <ns2:response xmlns:ns2="http://stackoverflow.com/">
            <trackingId>1375321435</trackingId>
            <responseCode>202</responseCode>
            <responseDescription>Request completed successfully</responseDescription>
            <detail>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?> &lt;LoanProcessResponse>     &lt;ResponseCode>E4284&lt;/ResponseCode>     &lt;ResponseDescription>The minimum value date allowed for this account must be greater than [08-12-2022].: acctDisburseTranLA.valueDate&lt;/ResponseDescription>     &lt;status>FAILURE&lt;/status> &lt;/LoanProcessResponse></detail>
        </ns2:response>
    </soap:Body>
</soap:Envelope>
and my query looks like the below

WITH XMLNAMESPACES('http://google.com/' AS soap, 'http://stackoverflow.com/' AS ns2)
SELECT
    timeSent, 
    accountNo,
    isSuccessful,
    try_convert(xml, responsePayload).query('/soap:Envelope/soap:Body/ns2:response/detail/LoanProcessResponse/ResponseDescription') AS response
from my_table
where accountNo = '000000008'
ORDER BY timesent desc;

Can you help me get the value of the  <ResponseDescription> without the tag?

Please try the following solution.

It is better to use XML data type for the responsePayload column.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (id INT IDENTITY PRIMARY KEY, responsePayload NVARCHAR(MAX));
INSERT @tbl (responsePayload) VALUES
(N'<soap:Envelope xmlns:soap="http://google.com/">
    <soap:Body>
        <ns2:response xmlns:ns2="http://stackoverflow.com/">
            <trackingId>1375321435</trackingId>
            <responseCode>202</responseCode>
            <responseDescription>Request completed successfully</responseDescription>
            <detail>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?> &lt;LoanProcessResponse>     &lt;ResponseCode>E4284&lt;/ResponseCode>     &lt;ResponseDescription>The minimum value date allowed for this account must be greater than [08-12-2022].: acctDisburseTranLA.valueDate&lt;/ResponseDescription>     &lt;status>FAILURE&lt;/status> &lt;/LoanProcessResponse></detail>
        </ns2:response>
    </soap:Body>
</soap:Envelope>');
-- DDL and sample data population, end

;WITH XMLNAMESPACES('http://google.com/' AS soap, 'http://stackoverflow.com/' AS ns2)
SELECT ID 
    , responseDescription = TRY_CAST(responsePayload AS XML)
        .value('(/soap:Envelope/soap:Body/ns2:response/responseDescription/text())[1]', 'VARCHAR(200)')
FROM @tbl;

Output

ID responseDescription
1 Request completed successfully

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