[英]Split XML variable, join and insert into a temp table XML column
I have an XML
variable that contains the following XML
: 我有一个包含以下
XML
的XML
变量:
<Fruits>
<Fruit>
<Type>Apple</Type>
<FruitID>1</FruitID>
<MoreInfo>
<Info Name="GreenApples" Value="3900" />
</MoreInfo>
</Fruit>
<Fruit>
<Type>Orange</Type>
<FruitID>2</FruitID>
<MoreInfo>
<Info Name="Oranges" Value="1100" />
</MoreInfo>
</Fruit>
</Fruits>
I am trying to create a temp table that looks like that: 我正在尝试创建一个看起来像这样的临时表:
CREATE TABLE #XmlTable (
email nvarchar(100),
xmlNode XML
)
The output that I am aiming for is: 我的目标是:
email | xmlNode
one@email.com | <Fruit><Type>Apple</Type><FruitID>1</FruitID><MoreInfo><Info Name="GreenApples" Value="3900" /></MoreInfo></Fruit>
two@email.com | <Fruit><Type>Orange</Type><FruitID>2</FruitID><MoreInfo><Info Name="Oranges" Value="1100" /></MoreInfo></Fruit>
The problem is that I don't know how to convert it to XML when I split it and insert it in the table. 问题是当我拆分它并将其插入表中时,我不知道如何将其转换为XML。
I have the following SQL that is doing the job, but how do I convert it to XML? 我有以下SQL正在完成这项工作,但我如何将其转换为XML?
INSERT INTO #XmlTable
SELECT EOR.email,
xmlNode.Col.value('.', 'nvarchar(max)') AS XML
FROM @outputXML.nodes('/Fruits') xmlNode(Col)
CROSS APPLY @outputXML.nodes('/Fruits/Fruit/FruitID') xmlValue(i)
INNER JOIN #EmailsOfReceivers EOR
ON EOR.ID= xmlValue.i.value('.','nvarchar(max)')
It works fine, but of course the xmlNode column doesn't have the XML tags. 它工作正常,但当然xmlNode列没有XML标记。
Here is one possible way : 这是一种可能的方式:
INSERT INTO #XmlTable
SELECT EOR.email,
fruit.x.query('.') AS XML
FROM @outputXML.nodes('/Fruits/Fruit') fruit(x)
INNER JOIN #EmailsOfReceivers EOR
ON EOR.ID = fruit.x.value('FruitID[1]','nvarchar(max)')
Basically, shred the XML on <Fruit>
nodes, then you can use query()
instead of value()
to get the XML tags. 基本上,在
<Fruit>
节点上粉碎XML,然后您可以使用query()
而不是value()
来获取XML标记。
Side note: I'd return FruitID
as int
instead of nvarchar(max)
, if possible. 旁注:如果可能的话,我
FruitID
作为int
而不是nvarchar(max)
返回。
You can use .query('.')
for your xml column: 您可以将
.query('.')
用于xml列:
DECLARE @outputXML XML
SELECT @outputXML = '<Fruits>
<Fruit>
<Type>Apple</Type>
<FruitID>1</FruitID>
<MoreInfo>
<Info Name="GreenApples" Value="3900" />
</MoreInfo>
</Fruit>
<Fruit>
<Type>Orange</Type>
<FruitID>2</FruitID>
<MoreInfo>
<Info Name="Oranges" Value="1100" />
</MoreInfo>
</Fruit>
</Fruits>'
INSERT INTO #XmlTable
SELECT EOR.email,
xmlNode.Col.query('.') AS MyXML
FROM @outputXML.nodes('/Fruits/Fruit') xmlNode(Col)
INNER JOIN #EmailsOfReceivers EOR
ON EOR.ID = xmlNode.Col.value('FruitID[1]','nvarchar(max)')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.