【问题标题】:How to filter xml data type column in SQL Server如何在 SQL Server 中过滤 xml 数据类型列
【发布时间】:2021-10-04 16:12:37
【问题描述】:

我有一个包含两个 xml 列的表,表中的数据很大。我想过滤 xml 类型的列以检查它是否包含 ID。

我的示例 xml 列 IncomingXML 和值如下所示:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sws="abc">
    <soapenv:Header>
        <To xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none" soapenv:mustUnderstand="1">abc</To>
        <Action xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none" soapenv:mustUnderstand="1">student</Action>
    </soapenv:Header>
    <soapenv:Body>
        <sws:ProvisionStudent>
          <sws:provisionStudentInput>
            <sws:Operation>U</sws:Operation>
            <sws:ADAccount>SU123456789</sws:ADAccount>
            <sws:ADPassword>abcde</sws:ADPassword>
            <sws:Prefix />
            <sws:FirstName>ancd</sws:FirstName>
            <sws:LastName>xyz</sws:LastName>
            <sws:MiddleName />
            <sws:Suffix />
            <sws:Email>abc@yahoo.com</sws:Email>
            <sws:EmplId>123456789</sws:EmplId>
            <sws:CampusCode />
            <sws:CompletionYear>0</sws:CompletionYear>
            <sws:CurrentCumulativeGpa>0</sws:CurrentCumulativeGpa>
            <sws:GraduationGpa />
            <sws:GraduationProgramCode />
            <sws:ProgramCode />
            <sws:UserType />
          </sws:provisionStudentInput>
        </sws:ProvisionStudent>
    </soapenv:Body>
</soapenv:Envelope>

请帮我查询类似

select * 
from table 
where IncomingXML like '%SU123456789%'

我尝试了以下但没有任何运气。

select * 
from table 
where cast(IncomingXML as nvarchar(max)) like '%SU123456789%'

【问题讨论】:

  • 虽然 CAST 方法与制定 XQuery 相比是粗略的,但它是 does in fact work,所以如果您没有得到任何结果,它强烈表明 XML 不是您认为的那样。
  • 它可能有效,但是根据我在该表中的数据,需要很长时间才能给出结果。

标签: sql-server sqlxml xquery-sql


【解决方案1】:

您可以为此使用 XQuery

DECLARE @toSearch nvarchar(100) = 'SU123456789';

WITH XMLNAMESPACES(
    'http://schemas.xmlsoap.org/soap/envelope/' AS soapenv,
    DEFAULT 'abc'
)
SELECT *
FROM YourTable t
WHERE t.IncomingXML.exist('/soapenv:Envelope/soapenv:Body/ProvisionStudent/provisionStudentInput/ADAccount[text() = sql:variable("@toSearch")]') = 1;

在任何节点中搜索,以效率为代价

DECLARE @toSearch nvarchar(100) = 'SU123456789';

SELECT *
FROM YourTable t
WHERE t.IncomingXML.exist('//*[text() = sql:variable("@toSearch")]') = 1;

db<>fiddle

您显然也可以在 XQuery 中嵌入文字而不是变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    相关资源
    最近更新 更多