XML解析& T-SQL - 第3部分

时间:2013-11-07 20:16:06

标签: sql sql-server xml tsql

xml返回,部分内容如下:

<Order xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:d1p2="http://schemas.abccompany.com/oml/package/1.0" xmlns:d1p1="http://schemas.abccompany.com/oml/batch/1.0" xmlns="http://schemas.abccompany.com/oml/base/1.0" intendedUse="0" quoteBack="5062-JA$181-3282" d1p1:transactionId="00000000-0000-0000-0000-000000000000" d1p2:uri="asdfasd-afdadfs-adsasdf" d1p1:customerId="0" d1p1:userId="0" d1p1:enabled="false" d1p1:priority="Low" d1p1:frequency="0" d1p1:recordCount="0" d1p1:executionPeriod="Once">
  <Security xmlns="http://schemas.abccompany.com/oml/security/1.0">
    <RootCredentials username="ust_3dResults2" password="1234567" />
    <LocationID>abcd</LocationID>
    <AccountID>9876</AccountID>
    <CustomerUserReferenceID>ssmart</CustomerUserReferenceID>
  </Security>
</Order>

使用t-sql,我如何拉“AccountID”?我试过了:

;WITH xmlnamespaces('http://www.w3.org/2001/XMLSchema' AS xsd, DEFAULT 'http://www.w3.org/2001/XMLSchema')
SELECT adr.id, 
adr.omlinput,
adr.omlinput.value('(/Order/Security/AccountID)[1]', 'varchar(50)') AS [Results]
FROM [Reporting].[ApplicantDirectRequest] adr WITH (NOLOCK)
WHERE adr.OmlInput IS NOT NULL

;WITH xmlnamespaces('http://www.w3.org/2001/XMLSchema' AS xsd, DEFAULT 'http://www.w3.org/2001/XMLSchema')
SELECT adr.id, 
adr.omlinput,
adr.omlinput.value('(/xsd:Order/Security/AccountID)[1]', 'varchar(50)') AS [Results]
FROM [Reporting].[ApplicantDirectRequest] adr WITH (NOLOCK)
WHERE adr.OmlInput IS NOT NULL

1 个答案:

答案 0 :(得分:3)

试试这个:

;WITH xmlnamespaces('http://schemas.abccompany.com/oml/security/1.0' AS ns, 
                    'http://schemas.abccompany.com/oml/base/1.0' AS base)
SELECT 
    adr.id, 
    adr.omlinput.value('(/base:Order/ns:Security/ns:AccountID)[1]', 'int') AS [Results]
FROM 
    [Reporting].[ApplicantDirectRequest] adr
WHERE 
    ID = 1

棘手的部分是:<Order>元素具有base命名空间,而其下方的所有内容(<Security><AccountID>元素)都包含ns命名空间。

由于没有名称空间扩展到整个XML片段,因此您无法真正使用默认名称空间....