I have a table, contains an XML file in each row (column XMLRow). Each xml includes two parts, PartI and PartII. For each partI, we can have multiple PartII (SEQUENCE). I want to insert it into my database. The part one will be inserted into TableI and the second table for PartII is called TableII.
CREATE TABLE XMLDATA {
id INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
insertDate Datetime NOT NULL DEFAULT getdate(),
XMLRow XML NOT NULL
}
The below is an example of XMLRow in XMLDATA table,
<MessageFrame>
<messageNumber>20</messageNumber>
<value>
<BasicSafetyMessage>
<partI>
<msgCnt>127</msgCnt>
</partI>
<partII>
<SEQUENCE>
<partII-Id>0</partII-Id>
<partII-Value>BLUE</partII-Value>
</SEQUENCE>
<SEQUENCE>
<partII-Id>3</partII-Id>
<partII-Value>RED</partII-Value>
</SEQUENCE>
</partII>
</BasicSafetyMessage>
</value>
</MessageFrame>
The tables created as the following,
CREATE TABLE TABLEI {
id INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
messageNumber INT NOT NULL,
msgCnt INT NOT NULL
};
GO
CREATE TABLE TABLEII {
id INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
T1_id Not NULL REFERENCES TableI (id) ON DELETE CASCADE,
partII-Id INT NOT NULL,
partII-Value NVARCHAR(50) NOT NULL
};
GO
I have Identity Primary Keys in each table as there is no unique ID in the xml stored in the database.
DECLARE @docHandle INT
DECLARE @XML AS XML
EXEC sp_xml_preparedocument @docHandle OUTPUT, @XML
SELECT @XML = XMLRow FROM [XMLDATA]
INSERT INTO TableI (messageId, msgCnt)
SELECT messageNumber, msgCnt
FROM OPENXML (@docHandle, '/MessageFrame/value/BasicSafetyMessage/partI')
WITH (
messageNumber int '../../../messageId',
msgCnt int 'msgCnt',
)
INSERT INTO TableII (T1_id, partII-Id, partII-Value)
SELECT @XML = XMLRow FROM [XMLDATA]
SELECT T1_id, partII-Id , partII-Value
FROM OPENXML (@docHandle, '/MessageFrame/value/BasicSafetyMessage/PartII/SEQUENCE')
WITH (
T1_id int @@IDENTITY,
partII-Id int 'partII-Id',
partII-Value int 'partII-Value',
)
EXEC sp_xml_removedocument @docHandle
The result should have been like this,
**Table1**
------------------------
id messageNumber msgCnt
------------------------
1 20 127
**Table2**
-------------------------------
id T1_id partII-Id partII-Value
-------------------------------
1 1 0 BLUE
2 1 3 RED
The second INSERT INTO returns NULL. Can anyone help me with this please? Am I doing something wrong here?