2014-02-13 103 views
0

我有一個包含XML列的表中檢索值,我的數據看起來是這樣的:SQL查詢從XML列

<Entries> 
    <Entry Default="No" ValueId="1" Sequence="1" Deleted="Yes"><Undefined></Entry>  
    <Entry Default="No" ValueId="2" Sequence="1">Non-Purulent</Entry>  
    <Entry Default="No" ValueId="4" Sequence="2" Deleted="Yes">Sanguinous</Entry>  
    <Entry Default="No" ValueId="11" Sequence="2">Odor Present</Entry>  
    <Entry Default="No" ValueId="3" Sequence="3">Purulent</Entry>  
    <Entry Default="No" ValueId="5" Sequence="3" Deleted="Yes">Serosangiunous</Entry>  
    <Entry Default="No" ValueId="6" Sequence="4">Sanguineous</Entry>  
    <Entry Default="No" ValueId="7" Sequence="4" Deleted="Yes">Serosanguineous</Entry>  
    <Entry Default="No" ValueId="8" Sequence="5">Serous</Entry>  
    <Entry Default="No" ValueId="10" Sequence="6">Sero-sanguineous</Entry>  
    <Entry Default="No" ValueId="9" Sequence="7">Other</Entry>  
</Entries> 

我想要檢索不具有已刪除=「值是「屬性。我對使用XML查詢非常陌生,所以我會很感激所有我能得到的幫助。

回答

1

如果你寫SQL爲您的代碼和你真正的意思了SQL服務器 - 那麼你可以使用這樣的事情(假設你的表稱爲YourTable和指定持有XML被稱爲XmlColumn - 請適應你的實際情況):

-- define a CTE (Common Table Expression) and extract detail info from XML 
;WITH XmlCte AS 
(
    SELECT 
     ID, 
     XmlText = XC.value('(.)[1]', 'varchar(20)'), 
     XmlValueId = XC.value('(@ValueId)[1]', 'int'), 
     XmlSequence = XC.value('(@Sequence)[1]', 'int'), 
     XmlDeleted = XC.value('(@Deleted)[1]', 'varchar(10)') 
    FROM dbo.YourTable 
    CROSS APPLY XmlColumn.nodes('/Entries/Entry') AS XT(XC) 
) 
SELECT 
    XmlValueId, 
    XmlSequence, 
    XmlText 
FROM XmlCte 
WHERE XmlDeleted IS NULL 
+0

非常感謝marc_s。是的,我應該在這裏標記正確的RDBMS。我會記下這一點。是的,它是SQL服務器 –

0

marc_s,請標記你的RDBMS

你指的是SQL Server中offchance,這裏的一對Ë方式使用XQuery做

SELECT 
    Nodes.node.value('@Sequence', 'varchar(50)') AS Sequence, 
    Nodes.node.value('(./text())[1]', 'varchar(50)') AS Value 
FROM 
    MyTable xyz 
    cross apply xyz.XmlColumn.nodes('/Entries/Entry[not(@Deleted="Yes")]') as Nodes(node); 

SqlFiddle here

請注意,你需要讓你的XML明確定義,即<Undefined>。將需要添加到CDATA部分,否則您需要關閉標籤。