繁体   English   中英

SQL Server XML列过滤

[英]SQL Server xml column filtering

我有一个带有xml列的SQL Server表。 Xml列具有以下xml数据。

<organisation>
    <organisation id="1"> <p> Content by Interviewee1 </p1> <p> Interviewee1 is talking about organisation-1 </p1> </organisation>
    <organisation id="2"> <p> Content by Interviewee2 </p1> <p> Interviewee2 is talking about organisation-2 </p1> </organisation>
    <organisation id="1"> <p> Content by Interviewee3 </p1> <p> Interviewee3 is talking about organisation-1 </p1> </organisation>
</organisation>

我需要按组织ID进行过滤。 例如,如果我按Id = 1进行过滤,则预期以下xml。

<organisation>
    <organisation id="1"> <p> Content by Interviewee1 </p1> <p> Interviewee1 is talking about organisation-1 </p1> </organisation>
    <organisation id="1"> <p> Content by Interviewee3 </p1> <p> Interviewee3 is talking about organisation-1 </p1> </organisation>
</organisation>

这是一种方法:

DECLARE @T TABLE (X XML)

INSERT INTO @T
        ( X )
VALUES  ( '<organisation>
    <organisation id="1"> <p> Content by Interviewee1 </p> <p1> Interviewee1 is talking about organisation-1 </p1> </organisation>
    <organisation id="2"> <p> Content by Interviewee2 </p> <p1> Interviewee2 is talking about organisation-2 </p1> </organisation>
    <organisation id="1"> <p> Content by Interviewee3 </p> <p1> Interviewee3 is talking about organisation-1 </p1> </organisation>
</organisation>'
          )

DECLARE @ID INT = 1


SELECT X.query('<organisation> 
                {for $o in /organisation/organisation
                where $o[@id=sql:variable("@ID")]
                return $o
                } </organisation>' )
FROM @T 

这是另一个...我将CDATA标记添加到您的XML节点以保留html标记,但是我不知道这是否适合您。 希望能有所帮助(Stuart Ainsworth提交的第一个答案看上去比这个答案更干净,更好)

DECLARE @columnData XML =
'<organisation>
    <organisation id="1"> <![CDATA[ <p> Content by Interviewee1 </p> <p> Interviewee1 is talking about organisation-1 </p> ]]></organisation>
    <organisation id="2"> <![CDATA[ <p> Content by Interviewee2 </p> <p> Interviewee2 is talking about organisation-2 </p> ]]></organisation>
    <organisation id="1"> <![CDATA[ <p> Content by Interviewee3 </p> <p> Interviewee3 is talking about organisation-1 </p> ]]></organisation>
</organisation>'

DECLARE @temporaryXMLtable TABLE (organisation XML)
INSERT INTO @temporaryXMLtable
SELECT 
fctn.arg.query('.')
FROM @columnData.nodes('/organisation/organisation')
fctn(arg)

DECLARE @filteredXML XML
SET @filteredXML = (SELECT 
        t.organisation.value('(organisation/@id)[1]','VARCHAR(MAX)') AS '@id',
        t.organisation.value('organisation[1]','VARCHAR(MAX)')
    FROM (SELECT organisation from @temporaryXMLtable WHERE (SELECT     organisation.value('(organisation/@id)[1]','VARCHAR(20)')) <> 2)
    t(organisation)
    FOR XML PATH('organisation'), ROOT('organisation'))

SELECT @filteredXML

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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