![](/img/trans.png)
[英]Where clause on a SQL Server XML column filtering on attribute AND value
[英]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.