Insert Parent-Child related data using OPENXML
From: Bhavesh (Bhavesh_at_discussions.microsoft.com)
Date: 10/05/04
- Next message: John Mas: "Problems getting all the data back with a XML query"
- Previous message: Rebecca: "Re: sqlxml bulkload limit?"
- Next in thread: Adam Machanic: "Re: Insert Parent-Child related data using OPENXML"
- Reply: Adam Machanic: "Re: Insert Parent-Child related data using OPENXML"
- Messages sorted by: [ date ] [ thread ]
Date: Tue, 5 Oct 2004 05:49:03 -0700
I have two classes Groups and Members and when I serialize (using
XmlSerializer) the object of Group class gives me the the xml string which I
am passing to the Stored procedure.
In the SP, I am trying to insert parent child records using openxml. My
Object Schema is such that I am not able to insert more than one child record
into the table.
The Schema for my class is as below:
public class Members
{
[XmlElement]
public int[] ID;
}
[Serializable]
public class Groups
{
public Members[] Group;
}
Below is my code for reference:
DROP TABLE GroupUsers
CREATE TABLE [dbo].[GroupUsers] (
[GroupID] [int] NOT NULL ,
[MemID] [int] NOT NULL
) ON [PRIMARY]
GO
DROP TABLE Groups
CREATE TABLE [dbo].[Groups] (
[GroupID] [int] IDENTITY (1, 1) NOT NULL ,
[CourseID] [int] NULL,
[ImportID] [int] NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Groups] WITH NOCHECK ADD
CONSTRAINT [PK_Groups] PRIMARY KEY CLUSTERED
(
[GroupID]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[GroupUsers] ADD
CONSTRAINT [FK_GroupUsers_Groups] FOREIGN KEY
([GroupID]
) REFERENCES [dbo].[Groups] (
[GroupID])
GO
DECLARE @doc int
exec sp_xml_preparedocument @doc OUTPUT,
'<Groups>
<Group>
<Members>
<ID>1</ID>
<ID>2</ID>
<ID>3</ID>
</Members>
</Group>
<Group>
<Members>
<ID>2</ID>
<ID>3</ID>
<ID>4</ID>
</Members>
</Group>
<Group>
<Members>
<ID>4</ID>
<ID>7</ID>
<ID>9</ID>
</Members>
</Group>
</Groups>'
INSERT INTO Groups (CourseID, ImportID)
SELECT 30, XMLId
FROM OpenXML(@doc,'//Groups/Group', 2)
WITH (XMLId int '@mp:id')
INSERT INTO GroupUsers (GroupID, MemID)
SELECT Groups.GroupID, ID
FROM OpenXML(@doc,'//Groups/Group/Members', 2)
WITH (XMLParentID int '@mp:parentid',
ID int) AS oxml
JOIN Groups ON oxml.XMLParentID = Groups.ImportID
EXEC sp_xml_removedocument @doc
select * from Groups
select * from GroupUsers
Can anybody tell me what I am doing wrong? Only one members gets inserted
against a group in the GroupUsers table instead of 3.
It's very URGENT!
Bhavesh
- Next message: John Mas: "Problems getting all the data back with a XML query"
- Previous message: Rebecca: "Re: sqlxml bulkload limit?"
- Next in thread: Adam Machanic: "Re: Insert Parent-Child related data using OPENXML"
- Reply: Adam Machanic: "Re: Insert Parent-Child related data using OPENXML"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|