我正在尝试插入" DocumentFields"从XML到SQL Server 2008的值,但没有运气。
你能帮我解决这个问题吗?下面是XML和使用的存储过程。
CREATE PROCEDURE [dbo].[SP_Test]
(@xmlData As XML)
AS
BEGIN
DECLARE @idoc int
SET @xmlData='<?xml version="1.0" encoding="UTF-8"?>
<ImportSession>
<Documents>
<Document DocumentClassName="RDOCCLASS" Processed="0" Priority="2">
<DocumentFields>
<DocumentField Name="DocumentID" Value="419" />
<DocumentField Name="MessageID" Value="apap-12w-asqwe" />
<DocumentField Name="AccountName" Value="John Thomas" />
<DocumentField Name="AccountNumber" Value="1234567890" />
<DocumentField Name="Contact" Value="00012736782345" />
</DocumentFields>
</Document>
</Documents>
</ImportSession>'
EXEC sp_xml_preparedocument @idoc OUTPUT, @xmlData;
INSERT INTO dbo.[Account]([DocumentID], [MessageID], [AccountName], [AccountNumber], [Contact])
SELECT *
FROM OPENXML(@idoc,/ImportSession/Documents/Document/DocumentFields',1)
WITH (DocumentID varchar(20),MessageID varchar(30),
AccountName varchar(20),AccountNumber varchar(20),
Contact varchar(20)
);
EXEC sp_xml_removedocument @xmlData;
END
由于 ARSH
答案 0 :(得分:3)
OPENXML绝对过时了。这是以现代方式从XML变量获取数据的方式:
DECLARE @xmlData XML='<?xml version="1.0" encoding="UTF-8"?>
<ImportSession>
<Documents>
<Document DocumentClassName="RDOCCLASS" Processed="0" Priority="2">
<DocumentFields>
<DocumentField Name="DocumentID" Value="419" />
<DocumentField Name="MessageID" Value="apap-12w-asqwe" />
<DocumentField Name="AccountName" Value="John Thomas" />
<DocumentField Name="AccountNumber" Value="1234567890" />
<DocumentField Name="Contact" Value="00012736782345" />
</DocumentFields>
</Document>
</Documents>
</ImportSession>';
SELECT Doc.value('(DocumentFields/DocumentField[@Name="DocumentID"]/@Value)[1]','int') AS DocumentID
,Doc.value('(DocumentFields/DocumentField[@Name="MessageID"]/@Value)[1]','varchar(max)') AS MessageID
,Doc.value('(DocumentFields/DocumentField[@Name="AccountName"]/@Value)[1]','varchar(max)') AS AccountName
,Doc.value('(DocumentFields/DocumentField[@Name="AccountNumber"]/@Value)[1]','varchar(max)') AS AccountNumber
,Doc.value('(DocumentFields/DocumentField[@Name="Contact"]/@Value)[1]','varchar(max)') AS Contact
FROM @xmlData.nodes('/ImportSession/Documents/Document') AS One(Doc)
所以你的SP应该是这样的:
Create PROCEDURE [dbo].[SP_Test]
(
@xmlData As XML
)
As
BEGIN
INSERT INTO dbo.[Account]([DocumentID],
[MessageID],
[AccountName],
[AccountNumber],
[Contact]
)
SELECT Doc.value('(DocumentFields/DocumentField[@Name="DocumentID"]/@Value)[1]','int') AS DocumentID
,Doc.value('(DocumentFields/DocumentField[@Name="MessageID"]/@Value)[1]','varchar(max)') AS MessageID
,Doc.value('(DocumentFields/DocumentField[@Name="AccountName"]/@Value)[1]','varchar(max)') AS AccountName
,Doc.value('(DocumentFields/DocumentField[@Name="AccountNumber"]/@Value)[1]','varchar(max)') AS AccountNumber
,Doc.value('(DocumentFields/DocumentField[@Name="Contact"]/@Value)[1]','varchar(max)') AS Contact
FROM @xmlData.nodes('/ImportSession/Documents/Document') AS One(Doc);
END