简体   繁体   中英

Returning multiple rows from querying XML column in SQL Server 2008

I have a table RDCAlerts with the following data in a column of type XML called AliasesValue :

<aliases>
  <alias>
    <aliasType>AKA</aliasType>
    <aliasName>Pramod Singh</aliasName>
  </alias>
  <alias>
    <aliasType>AKA</aliasType>
    <aliasName>Bijoy Bora</aliasName>
  </alias>
</aliases>

I would like to create a query that returns two rows - one for each alias and I've tried the following query:

SELECT
   AliasesValue.query('data(/aliases/alias/aliasType)'),
   AliasesValue.query('data(/aliases/alias/aliasName)'),
FROM [RdcAlerts]

but it returns just one row like this:

AKA AKA | Pramod Singh Bijoy Bora

Look at the .nodes() method in Books Online:

DECLARE @r TABLE (AliasesValue XML)
INSERT INTO @r 
SELECT '<aliases>   <alias>     <aliasType>AKA</aliasType>     <aliasName>Pramod Singh</aliasName>   </alias>   <alias>     <aliasType>AKA</aliasType>     <aliasName>Bijoy Bora</aliasName>   </alias> </aliases> '


SELECT c.query('data(aliasType)'), c.query('data(aliasName)')
FROM @r r CROSS APPLY AliasesValue.nodes('aliases/alias') x(c)

You need to use the CROSS APPLY statement along with the .nodes() function to get multiple rows returned.

select 
    a.alias.value('(aliasType/text())[1]', 'varchar(20)') as 'aliasType', 
    a.alias.value('(aliasName/text())[1]', 'varchar(20)') as 'aliasName' 
from 
    RDCAlerts r
    cross apply r.AliasesValue.nodes('/aliases/alias') a(alias)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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