Reputation: 11125
For a table schema like below
CREATE TABLE [dbo].[Employee](
[EmployeeId] [uniqueidentifier] NOT NULL,
[Name] [nvarchar](50) NOT NULL,
[Location] [nvarchar](50) NOT NULL,
[Skills] [xml] NOT NULL,
[Projects] [nvarchar](400) NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
When inserting data into table, i want to insert only child tags of <SkillSet>
but seems <SkillSet>
along with it's child elements inserts into Skill xml columns.
declare @doc NVARCHAR(MAX)
declare @idoc INT
select @doc = '<Request Type="InsertEmployee" CRUD="C">
<Employee>
<EmployeeId>1</EmployeeId>
<Name>Deeptechtons</Name>
<Location>USA</Location>
<SkillSet>
<Skill>C#</Skill>
<Skill>SQL Server 2005</Skill>
<Skill>ASP.net</Skill>
</SkillSet>
<Projects>
<Project>LowBin</Project>
<Project>Maskin</Project>
</Projects>
</Employee>
</Request>'
exec sp_xml_preparedocument @idoc output,@doc
insert into Employee (
EmployeeId
,[Name]
,Location
,Skills,
Projects
)
SELECT NEWID()
,[Name]
,Location
,Skills
,Projects
FROM OPENXML(@idoc,'Request/Employee',2)
WITH
(
[Name] NVARCHAR(50)
,Location NVARCHAR(50)
,Skills XML 'SkillSet'
,Projects NVARCHAR(400)
)
exec sp_xml_removedocument @idoc
How to insert only child elements of <Skillset>
rather than whole tag and its children.
I expected Projects
also to be inserted same as did but only Lowbin
content of first Project tag is inserted. Can you correct my code.
Upvotes: 1
Views: 1203
Reputation: 138960
Since you are on SQL Server 2005 you can make use of the XML data type and do like this instead.
declare @doc xml
select @doc = '<Request Type="InsertEmployee" CRUD="C">
<Employee>
<EmployeeId>1</EmployeeId>
<Name>Deeptechtons</Name>
<Location>USA</Location>
<SkillSet>
<Skill>C#</Skill>
<Skill>SQL Server 2005</Skill>
<Skill>ASP.net</Skill>
</SkillSet>
<Projects>
<Project>LowBin</Project>
<Project>Maskin</Project>
</Projects>
</Employee>
</Request>'
insert into Employee (
EmployeeId
,[Name]
,Location
,Skills,
Projects
)
select newid(),
T.N.value('Name[1]', 'nvarchar(50)'),
T.N.value('Location[1]', 'nvarchar(50)'),
T.N.query('SkillSet/*'),
cast(T.N.query('Projects/*') as nvarchar(400))
from @doc.nodes('/Request/Employee') as T(N)
Result:
BC76E37C-0C0D-4B7B-92FD-0F7807F9204B
Deeptechtons
USA
<Skill>C#</Skill><Skill>SQL Server005</Skill>Skill>ASP.net</Skill>
<Project>LowBin</Project><Project>Maskin</Project>
Update:
If you really want to use OPENXML for some reason you can use this.
insert into Employee (
EmployeeId
,[Name]
,Location
,Skills,
Projects
)
SELECT NEWID()
,[Name]
,Location
,Skills.query('SkillSet/*')
,cast(Projects.query('Projects/*') as nvarchar(max))
FROM OPENXML(@idoc,'Request/Employee',2)
WITH
(
[Name] NVARCHAR(50)
,Location NVARCHAR(50)
,Skills XML 'SkillSet'
,Projects XML
)
Upvotes: 1