我需要从表中提取XML,使用空值:
<RoomNo xsi:nil="true" />
所以我使用元素xsinil :
for xml path('root'), elements xsinil
我的问题在于提取由子查询构成的复杂XML。子句元素xsinil 在每个子查询中插入代码 xmlns:xsi =“http://www.w3.org/2001/XMLSchema-instance”
如果删除内部元素xsinil ,我会丢失空字段。
使用此查询:
-- Test table
CREATE TABLE #TestTable (StudentName VARCHAR(100), Course VARCHAR(100), Instructor VARCHAR(100), RoomNo VARCHAR(100))
GO
INSERT INTO #TestTable (StudentName, Course, Instructor, RoomNo)
SELECT 'Mark', 'Algebra', 'Dr. James', '101'
UNION ALL
SELECT 'Mark', 'Maths', 'Dr. Jones', '201'
UNION ALL
SELECT 'Joe', 'Algebra', 'Dr. James', null
UNION ALL
SELECT 'Joe', 'Science', 'Dr. Ross', '301'
UNION ALL
SELECT 'Joe', 'Geography', 'Dr. Lisa', null
UNION ALL
SELECT 'Jenny', 'Algebra', 'Dr. James', '101'
GO
-- Xpath query
select -- node STUDENT
A.StudentName,
(
select -- node TEST
Instructor as '@Instructor', Course as 'Course', RoomNo as 'RoomNo'
from #TestTable B where B.StudentName = A.StudentName
for xml path('test'), type, elements xsinil
) as 'node()'
from (select distinct StudentName from #TestTable) A
for xml path('student'), root('root'), type, elements xsinil
-- end
drop TABLE #TestTable
我得到了:
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<student>
<StudentName>Jenny</StudentName>
<test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Instructor="Dr. James">
<Course>Algebra</Course>
<RoomNo>101</RoomNo>
</test>
</student>
<student>
<StudentName>Joe</StudentName>
<test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Instructor="Dr. James">
<Course>Algebra</Course>
<RoomNo xsi:nil="true" />
</test>
<test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Instructor="Dr. Ross">
<Course>Science</Course>
<RoomNo>301</RoomNo>
</test>
<test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Instructor="Dr. Lisa">
<Course>Geography</Course>
<RoomNo xsi:nil="true" />
</test>
</student>
<student>
<StudentName>Mark</StudentName>
<test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Instructor="Dr. James">
<Course>Algebra</Course>
<RoomNo>101</RoomNo>
</test>
<test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Instructor="Dr. Jones">
<Course>Maths</Course>
<RoomNo>201</RoomNo>
</test>
</student>
</root>
但我需要:
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<student>
<StudentName>Jenny</StudentName>
<test Instructor="Dr. James">
<Course>Algebra</Course>
<RoomNo>101</RoomNo>
</test>
</student>
<student>
<StudentName>Joe</StudentName>
<test Instructor="Dr. James">
<Course>Algebra</Course>
<RoomNo xsi:nil="true" />
</test>
<test Instructor="Dr. Ross">
<Course>Science</Course>
<RoomNo>301</RoomNo>
</test>
<test Instructor="Dr. Lisa">
<Course>Geography</Course>
<RoomNo xsi:nil="true" />
</test>
</student>
<student>
<StudentName>Mark</StudentName>
<test Instructor="Dr. James">
<Course>Algebra</Course>
<RoomNo>101</RoomNo>
</test>
<test Instructor="Dr. Jones">
<Course>Maths</Course>
<RoomNo>201</RoomNo>
</test>
</student>
</root>