我尝试从“StkPart”属性中选择每个PartNum,WarehouseCode和OnhandQty,然后从“Plant”属性中选择工厂。此xml文件中只有一个“Plant”,“Plant”将与“StkPart”属性中的每一行相关联。
例如:
PartNum WarehouseCode OnhandQty Plant
1. 10-12345 Corona 150 MfgSys
2. 10-12351 Cork 1 MfgSys
3. 10-51617a Here 198 MfgSys
4. 10-97654 There 67 MfgSys
这就是我一直在尝试的(XML代码在底部): 此代码可以工作并将数据输入我的表格:
USE Database
GO
CREATE TABLE XMLwithOpenXML
(
Id INT IDENTITY PRIMARY KEY,
XMLData XML,
LoadedDateTime DATETIME
)
INSERT INTO XMLwithOpenXML(XMLData, LoadedDateTime)
SELECT CONVERT(XML, BulkColumn) AS BulkColumn, GETDATE()
FROM OPENROWSET(BULK 'C:\Test\StockStatusReport30597.XML', SINGLE_BLOB) AS x;
SELECT * FROM XMLwithOpenXML
然后我尝试选择数据,但这不起作用:
USE Database
GO
DECLARE @XML AS XML, @hDoc AS INT, @SQL NVARCHAR (MAX)
SELECT @XML = XMLData FROM XMLwithOpenXML
EXEC sp_xml_preparedocument @hDoc OUTPUT, @XML
SELECT PartNum
FROM OPENXML(@hDoc, 'ReportDataSet/PartNum')
WITH
(
PartNum [varchar](50) '@PartNum'
)
EXEC sp_xml_removedocument @hDoc
GO
如何让上述代码生效?
以下是要下载的XML文件: http://wikisend.com/download/101282/StockStatusReport30597.XML
答案 0 :(得分:1)
这可能会有所帮助
Declare @xml xml = N'<ReportDataSet
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
...
</ReportDataSet>'
Select
N.value('PartNum[1]', 'varchar(20)') PartNum,
N.value('WarehouseCode[1]', 'varchar(20)') WarhouseCode,
N.value('OnhandQty[1]', 'int') OnhandQty,
@xml.value('(/ReportDataSet/Plant/Plant)[1]', 'varchar(20)') Plant
from
@xml.nodes('/ReportDataSet/StkPart') as T(n)
我已经从下面的示例中删除了一些东西以适应SQLFiddle的限制,但是它使用了添加了适当命名空间的问题的查询:
<强> Example SQLFiddle 强>
对于大数据示例,您需要为查询设置默认命名空间:
With xmlnamespaces (default 'http://www.epicor.com/Mfg/100')
Select
N.value('PartNum[1]', 'varchar(20)') PartNum,
N.value('WarehouseCode[1]', 'varchar(20)') WarhouseCode,
N.value('OnhandQty[1]', 'decimal(10,2)') OnhandQty,
@xml.value('(/ReportDataSet/Plant/Plant)[1]', 'varchar(20)') Plant
from
@xml.nodes('/ReportDataSet/StkPart') as T(n)