你是对的,你.modify()
一次只能用于一个动作......
以下代码有一些假设:
- 在您的示例中,第二行
Addresses
应该有EntityId=7
- 两个表的 XML 中都有预先存在的内容
您可以使用可更新的 CTE。此 CTE 将从表中选择Addresses
给定 ID 的所有 XML 列并添加计算列Address
。
现在我们可以使用修改,一次将所有组合的地址条目插入到一个操作中:
DECLARE @address TABLE (ID INT,[Address] XML);
INSERT INTO @address VALUES
(5, N'<Address id="5a" ><Street>Some Street</Street></Address>')
,(5, N'<Address id="5b" ><Street>Some Other</Street></Address>')
,(7, N'<Address id="7" ><Street>One More</Street></Address>');
DECLARE @addresses TABLE (ID INT,AddrXML XML);
INSERT INTO @addresses VALUES
(5, N'<Addresses><PreexistingContent>Blah</PreexistingContent></Addresses>')
,(7, N'<Addresses><PreexistingContent>Booh</PreexistingContent></Addresses>');
WITH CombinedAddress AS
(
SELECT adrs.ID
,(
SELECT adr.[Address]
FROM @address AS adr
WHERE adr.ID=adrs.ID
FOR XML PATH(''),TYPE
) AS Combined
,adrs.AddrXML
FROM @addresses AS adrs
)
UPDATE CombinedAddress
SET AddrXML.modify(N'insert sql:column("Combined") as last into (/Addresses)[1]');
SELECT * FROM @addresses
ID=5 的结果
<Addresses>
<PreexistingContent>Blah</PreexistingContent>
<Address>
<Address id="5a">
<Street>Some Street</Street>
</Address>
</Address>
<Address>
<Address id="5b">
<Street>Some Other</Street>
</Address>
</Address>
</Addresses>
更新地址未嵌套
尝试这个:
WITH CombinedAddress AS
(
SELECT adrs.ID
,(
SELECT adr.[Address] AS [*]
FROM @address AS adr
WHERE adr.ID=adrs.ID
FOR XML PATH(''),TYPE
) AS Combined
,adrs.AddrXML
FROM @addresses AS adrs
)
UPDATE CombinedAddress
SET AddrXML.modify(N'insert sql:column("Combined") as last into (/Addresses)[1]');
结果
<Addresses>
<PreexistingContent>Blah</PreexistingContent>
<Address id="5a">
<Street>Some Street</Street>
</Address>
<Address id="5b">
<Street>Some Other</Street>
</Address>
</Addresses>