如何使用sp_xml_preparedocument和OPENXML

时间:2014-04-27 16:56:06

标签: sql-server

我有以下xml代码我想在表中提取数据,但由于Select语句没有返回任何值,因此无法继续进行。请指导我。感谢

DECLARE @hdoc_B2C INT,@doc varchar(1000);
SET @doc ='
<ROOT>
  <CLIENTDETAILS  STATUSID= "1" STATUSNAME= "Active" TRANSMISSIONTYPEID= "1" TRANSMISSIONTYPENAME= "EMail" NAME= "Agente creato via API" SHORTNAME= "APIMATT" DONOTEMAIL= "0" FINALSIEBELCHILDDELETED= "0" LANGUAGEID= "1" PREFERREDORGANISATIONID= "2"/>
  <ADDRESSES>
    <ADDRESS  ADDRESSID= "0" CLIENTID= "0" ADDRESSLINE1= "prima riga" ADDRESSLINE2= "seconda riga" ADDRESSLINE3= "terza riga" 
ADDRESSLINE4= "quarta riga" ADDRESSPOSTCODE= "00185" ADDRESSCITY= "Rome" ADDRESSPHONENUMBER= "+0000000" `enter code here`
ADDRESSFAXNUMBER= "+000000000" ADDRESSEMERGENCYPHONENUMBER= "+000000000" ADDRESSEMAILADDRESS= "xyz@test.com" 
ADDRESSWEBSITEURL= "www.test.com" ADDRESSTYPEID= "2" ADDRESSTYPENAME= "Main" ADDRESSSTATEID= "0" ADDRESSSTATENAME= "" 
ADDRESSCOUNTRYID= "5" ADDRESSCOUNTRYNAME= "Italy" CRMID= "" DUMMYADDRESS= "0"/>
  </ADDRESSES>
  <NOTES></NOTES>
  <GROUPS></GROUPS>
  <MEMBERSHIPS></MEMBERSHIPS>
  <LOSTNMERGES></LOSTNMERGES>
</ROOT>'

SELECT *FROM OPENXML (@hDoc_B2C,'//ClientDetails') WITH (StatusID INT, StatusName VARCHAR(50), TransmissionTypeID INT, 
            TransmissionTypeName VARCHAR(50), [Name] VARCHAR(50), ShortName VARCHAR(30), DoNotEmail BIT,
            FinalSiebelChildDeleted Int,LanguageID int)

1 个答案:

答案 0 :(得分:0)

请注意,Xml区分大小写,因此您需要调整Xpath和WITH变量以匹配文档,即:。

DECLARE @hdoc_B2C INT, @doc varchar(1000);
SET @doc ='your xml, without `enter code here`';

-- Obtain handle
EXEC sp_xml_preparedocument @hdoc_B2C OUTPUT, @doc;

SELECT *
FROM OPENXML 
(@hDoc_B2C,'//CLIENTDETAILS') 
WITH (
    STATUSID INT, 
    STATUSNAME VARCHAR(50), 
    TRANSMISSIONTYPEID INT, 
    TRANSMISSIONTYPENAME VARCHAR(50), 
    [NAME] VARCHAR(50), 
    SHORTNAME VARCHAR(30), 
    DONOTEMAIL BIT,
    FINALSIEBELCHILDDELETED Int,
    LANGUAGEID int
);

-- Free Handle
EXEC sp_xml_removedocument @hDoc_B2C;

SqlFiddle here

或者,您可以通过在ColPattern中提供xpath将Xml重新映射到不同的名称/结构

SELECT *
FROM OPENXML 
(@hDoc_B2C,'//CLIENTDETAILS') 
WITH (
    StatusId INT '@STATUSID', 
    Foo VARCHAR(50) '@STATUSNAME',     
    ...