2017-07-26 84 views
0

只是想在此處獲得一些幫助。我有一種情況,我需要從<Column Name>標籤中找到一些數據,如下面的XML所示。在SQL Server中使用XML列搜索特定的列名稱

我有一個問題,在系統中導出了一些格式不正確的數據,我發現這一塊,但現在有一個進程將數據導出系統。現在我有一個包含XML存儲的表。

我必須遍歷整個表來查看該列名是否存在於該特定ID列中,如果存在,我將返回該ID。舉例來說,我的表名是Sample,列是(ID,ImportXML)。

任何幫助我如何實現這一目標?從SQL Server內部處理XML的新手段。

<?xml version="1.0" encoding="UTF-8"?> 
<ExportConfiguration id="SampleExport"> 
    <definitions>  
     <ClientName Value="Sample"/>  
     <FileType Value="XML"/>  
     <FileName>  
      <Value Value="SomeValue"/>  
     </FileName> 
     <Columns> 
      <Column Name="abc" DataType="String" Value="test123"/>  
      <Column Name="findthis" DataType="String" Value="Test456"/>   
     </Columns> 
    </definitions> 
</ExportConfiguration> 

因此,從上述的代碼基本上我想從內<Columns>/<Column Name> = "findthis"所以基本上findthis是我的關鍵字獲得的價值,我想這僅僅包含了爭論的緣故關鍵字findthis列的所有的ID。

回答

3

事情是這樣的:

-- Test table. 
declare @xTable table (ID int identity(1,1) primary key clustered, XMLData xml) 

-- Insert an XML document. I only did one, but the same would work for multiple 
insert into @xTable 
select '<?xml version="1.0" encoding="UTF-8"?> 
      <ExportConfiguration id="SampleExport"> 
       <definitions>  
        <ClientName Value="Sample"/>  
        <FileType Value="XML"/>  
        <FileName>  
         <Value Value="SomeValue"/>  
        </FileName> 
        <Columns> 
         <Column Name="abc" DataType="String" Value="test123"/>  
         <Column Name="findthis" DataType="String" Value="Test456"/>   
        </Columns> 
       </definitions> 
      </ExportConfiguration>' 

-- Return everything from the table with your XML where there is an attribute at the path "/ExportConfiguration/definitions/Columns/Column" with the name "Name" and the value "findthis" 
select * 
from @xTable 
where XMLData.exist('/ExportConfiguration/definitions/Columns/Column[@Name eq "findthis"]') = 1 
+1

好答案!就像一個增強:如果在所有情況下都不相同,搜索字符串'「findthis」'可能通過'sql:variable()'或'sql:column()'引入... – Shnugo