2011-01-31 83 views
4

我使用TSQL/XML查詢我該如何實現這一結果有一個XML這種格式TSQL - XML查詢幫助

<tests> 
    <test> 
     <testid>1</testid> 
     <testval>8</testval> 
     <testname> 
      <testid>1</testid> 
      <testname>test 1</testname> 
     </testname> 
    </test> 
    <test> 
     <testid>2</testid> 
     <testval>5</testval> 
     <testname> 
      <testid>2</testid> 
      <testname>test 2</testname> 
     </testname> 
    </test> 
</tests> 

[Testid][TestVal][TestName] 
    1  8  Test 1 
    2  5  Test 2 
+0

是表中的字段或文件的XML? – 2011-01-31 07:06:19

回答

4

試試這個:

declare @input XML = '<tests> 
    <test> 
     <testid>1</testid> 
     <testval>8</testval> 
     <testname> 
      <testid>1</testid> 
      <testname>test 1</testname> 
     </testname> 
    </test> 
    <test> 
     <testid>2</testid> 
     <testval>5</testval> 
     <testname> 
      <testid>2</testid> 
      <testname>test 2</testname> 
     </testname> 
    </test> 
</tests>' 

select 
    Tests.value('(testid)[1]', 'int') as 'TestID', 
    Tests.value('(testval)[1]', 'int') as 'TestVal', 
    Tests.value('(testname/testname)[1]', 'varchar(20)') as 'TestName' 
FROM 
    @input.nodes('/tests/test') as List(Tests) 

這給你所需的輸出。

如果你有這些XML列的表,你可能需要使用一個稍微不同的方法(使用CROSS APPLY):

select 
    tbl.SomeValue, tbl.SomeOtherValue, 
    Tests.value('(testid)[1]', 'int') as 'TestID', 
    Tests.value('(testval)[1]', 'int') as 'TestVal', 
    Tests.value('(testname/testname)[1]', 'varchar(20)') as 'TestName' 
FROM 
    dbo.YourTable tbl 
CROSS APPLY 
    tbl.XmlColumn.nodes('/tests/test') as List(Tests) 
+0

作品...謝謝! – Juvil 2011-01-31 07:35:26