我有一个如下存储过程:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Sp_ComplexXml]
AS
BEGIN
DECLARE @XmlString xml
SET @XmlString =
'<ArrayOfSizeColorQuantityViewModel>
<ProductId>012312</ProductId>
<SizeColorQuantityViewModel>
<ColorId>Red</ColorId>
<SizeAndQuantities>
<SizeAndQuantity>
<SizeId>S</SizeId>
<Quantity>1</Quantity>
</SizeAndQuantity>
<SizeAndQuantity>
<SizeId>M</SizeId>
<Quantity>2</Quantity>
</SizeAndQuantity>
<SizeAndQuantity>
<SizeId>L</SizeId>
<Quantity>3</Quantity>
</SizeAndQuantity>
<SizeAndQuantity>
<SizeId>XL</SizeId>
<Quantity>4</Quantity>
</SizeAndQuantity>
</SizeAndQuantities>
</SizeColorQuantityViewModel>
<SizeColorQuantityViewModel>
<ColorId>Blue</ColorId>
<SizeAndQuantities>
<SizeAndQuantity>
<SizeId>S</SizeId>
<Quantity>1</Quantity>
</SizeAndQuantity>
<SizeAndQuantity>
<SizeId>M</SizeId>
<Quantity>2</Quantity>
</SizeAndQuantity>
<SizeAndQuantity>
<SizeId>L</SizeId>
<Quantity>3</Quantity>
</SizeAndQuantity>
<SizeAndQuantity>
<SizeId>XL</SizeId>
<Quantity>4</Quantity>
</SizeAndQuantity>
</SizeAndQuantities>
</SizeColorQuantityViewModel>
</ArrayOfSizeColorQuantityViewModel>'
INSERT INTO ProductSizeColor(ProductID, SizeID, ColorID, Quantity)
SELECT
SCQ.node.value('(../ProductId)[1]', 'bigint') as 'ProductID',
SCQ.node.value('(ColorId)[1]', 'varchar(3)') as 'ColorID',
SQ.i.value('(SizeId)[1]', 'varchar(3)') as 'SizeID',
SQ.i.value('(Quantity)[1]', 'int') as 'Quantity'
FROM
@XmlString.nodes('/ArrayOfSizeColorQuantityViewModel/SizeColorQuantityViewModel') as SCQ(node)
CROSS APPLY
SCQ.node.nodes('/SizeAndQuantities/SizeAndQuantity') as SQ(i)
END
我尝试将这个复杂的XML数据插入下表:
表:(3个外键)
我不知道解析XML代码是否有任何问题? 如果你不介意,请帮我找出来吗?
感谢您的帮助
答案 0 :(得分:1)
试试这段代码:
SELECT
SCQ.node.value('(../ProductId)[1]', 'bigint') as 'ProductID',
SCQ.node.value('(ColorId)[1]', 'varchar(4)') as 'ColorID',
SQ.i.value('(SizeId)[1]', 'varchar(3)') as 'SizeID',
SQ.i.value('(Quantity)[1]', 'int') as 'Quantity'
FROM
@XmlString.nodes('/ArrayOfSizeColorQuantityViewModel/SizeColorQuantityViewModel') as SCQ(node)
CROSS APPLY
SCQ.node.nodes('SizeAndQuantities/SizeAndQuantity') as SQ(i)
我刚刚从您的第二个XPath中删除了一个前导/
(在CROSS APPLY
中),我还将ColorId
值的长度扩展为varchar(4)
(允许为“蓝色”正确显示。
现在我从SELECT
获得此输出: