在SQL Server查询中使用For Xml子句,显式模式指定XMLNAMESPACE

时间:2012-07-09 08:31:33

标签: sql-server xml for-xml-explicit

我正在尝试使用FOR XML子句EXPLICIT模式查询某个数据库但我不知道如何在使用此模式时指定XMLNAMESPACE和模式,就像使用WITH XMLNAMESPACE一样{{1模式或AUTO

RAW示例查询在其结果中指定MSDN作为结果Schema1的模式

XML

以下是样本结果:

USE AdventureWorks2012;
GO
 SELECT  1 as Tag,
0 as Parent,
SalesOrderID  as [OrderHeader!1!SalesOrderID!id],
OrderDate     as [OrderHeader!1!OrderDate],
CustomerID    as [OrderHeader!1!CustomerID],
NULL          as [SalesPerson!2!SalesPersonID],
NULL          as [OrderDetail!3!SalesOrderID!idref],
NULL          as [OrderDetail!3!LineTotal],
NULL          as [OrderDetail!3!ProductID],
NULL          as [OrderDetail!3!OrderQty]
FROM   Sales.SalesOrderHeader
WHERE  SalesOrderID=43659 or SalesOrderID=43661
....
SELECT 3 as Tag,
 1 as Parent,
SOD.SalesOrderID,
NULL,
NULL,
SalesPersonID,
SOH.SalesOrderID,
LineTotal,
ProductID,
OrderQty   
FROM    Sales.SalesOrderHeader SOH,Sales.SalesOrderDetail SOD
 WHERE   SOH.SalesOrderID = SOD.SalesOrderID
 AND     (SOH.SalesOrderID=43659 or SOH.SalesOrderID=43661)
 ORDER BY [OrderHeader!1!SalesOrderID!id], [SalesPerson!2!SalesPersonID],
  [OrderDetail!3!SalesOrderID!idref],[OrderDetail!3!LineTotal]
 FOR XML EXPLICIT, XMLDATA

1 个答案:

答案 0 :(得分:2)

来自MSDN的查询包含一个模式,因为它使用XMLDATA指令。

  

指定内联XML-Data Reduced(XDR)架构应该是   回。架构作为内联架构预先添加到文档中。   有关工作示例,请参阅使用带有FOR XML的RAW模式。

如果要包含具有显式模式的命名空间,则必须自己添加它并相应地命名元素和属性。

declare @T table
(
  id int,
  title varchar(50)
)

insert into @T values(451, 'Receptionist')
insert into @T values(1025, 'Secretary')

select 1    as Tag,
       null as Parent,
       'xx.yy.zz' as [root!1!xmlns:ns],
       null as [ns:item!2!ns:id],
       null as [ns:item!2!ns:title]
union all
select 2    as Tag,
       1 as Parent,
       null,
       id,
       title
from @T 
for xml explicit

结果:

<root xmlns:ns="xx.yy.zz">
  <ns:item ns:id="451" ns:title="Receptionist" />
  <ns:item ns:id="1025" ns:title="Secretary" />
</root>