从SQL Server 2008中的查询XML列返回多行

时间:2022-12-22 01:39:18

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

我有一个表RDCAlerts,其中包含一个名为AliasesValue的XML类型列中的以下数据:

<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

2 个解决方案

#1


17  

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

查看联机丛书中的.nodes()方法:

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)

#2


14  

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

您需要使用CROSS APPLY语句和.nodes()函数来获取返回的多行。

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)

#1


17  

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

查看联机丛书中的.nodes()方法:

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)

#2


14  

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

您需要使用CROSS APPLY语句和.nodes()函数来获取返回的多行。

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)