如何将xml编码标记附加到XML结果集

时间:2014-02-07 08:01:00

标签: sql xml

我有两个问题来自以下SQL代码:

DECLARE @tbl TABLE(BookID int primary key,
                   Title varchar(50),
                   Author varchar(50),
                   Pages int);

INSERT INTO @tbl SELECT 1,'The Book', 'The Author', 20
INSERT INTO @tbl SELECT 2,'Another Book', 'Another Author', 20
INSERT INTO @tbl SELECT 3,'Book', 'Author', 20

SELECT Book.Title,
       (SELECT Details.BookID Ref, Details.Author, Details.Pages
        FROM @tbl Details
        FOR XML RAW ('Details'), type)
FROM @tbl Book
FOR XML RAW ('Book'), ROOT  ('Books') 

返回的结果集是:

<Books>
  <Book Title="The Book">
    <Details Ref="1" Author="The Author" Pages="20" />
    <Details Ref="2" Author="Another Author" Pages="20" />
    <Details Ref="3" Author="Author" Pages="20" />
  </Book>
  <Book Title="Another Book">
    <Details Ref="1" Author="The Author" Pages="20" />
    <Details Ref="2" Author="Another Author" Pages="20" />
    <Details Ref="3" Author="Author" Pages="20" />
  </Book>
  <Book Title="Book">
    <Details Ref="1" Author="The Author" Pages="20" />
    <Details Ref="2" Author="Another Author" Pages="20" />
    <Details Ref="3" Author="Author" Pages="20" />
  </Book>
</Books>

问题1:每本书重复多次细节标签,我只想要一本。 问题2:我想将<?xml version="1.0"?>追加到结果集的顶部。

2 个答案:

答案 0 :(得分:0)

通过在子查询中添加WHERE子句可以轻松解决第一个问题:

SELECT Book.Title,
       (SELECT Details.BookID Ref, Details.Author, Details.Pages
        FROM @tbl Details
        WHERE Details.BookID = Book.BookID --<-- Here
        FOR XML RAW ('Details'), type)
FROM @tbl Book
FOR XML RAW ('Book'), ROOT  ('Books') 

Re:XML声明,我不确定这么容易实现 - 大多数人似乎都是通过转换为文本来解决它而只是将字符串插在前面。

答案 1 :(得分:0)

可能有多种方法可以做到这一点。这是一个:

DECLARE @tbl TABLE(BookID int primary key,
               Title varchar(50),
               Author varchar(50),
               Pages int);

INSERT INTO @tbl SELECT 1,'The Book', 'The Author', 20
INSERT INTO @tbl SELECT 2,'Another Book', 'Another Author', 20
INSERT INTO @tbl SELECT 3,'Book', 'Author', 20


;WITH cte (XMLRESULT) AS (

SELECT Book.Title,
   (SELECT Details.BookID Ref, Details.Author, Details.Pages
    FROM @tbl Details
    FOR XML RAW ('Details'), type)
FROM @tbl Book
FOR XML RAW ('Book'), ROOT  ('Books') 

) 

SELECT  '<?xml version="1.0"?>' + XMLRESULT FROM cte