1

我有以下 SELECT 查询:

SELECT
'2012' 'period',
Person.Name 'users/person'
FROM Person
FOR XML PATH(''), ROOT ('company')

这给了我以下 XML:

<company>
  <period>2012</period>
  <users>
    <person>Dubach</person>
  </users>
  <period>2012</period>
  <users>
    <person>Pletscher</person>
  </users>
  <period>2012</period>
  ....

我想在结果 XML 的开头只使用一次“句点”标签。我怎样才能做到这一点?

4

3 回答 3

3
DECLARE @period XML = '<period>2012</period>'
DECLARE @xml XML = (
        SELECT 
        Person.Name 'users/person'
        FROM Person
        FOR XML PATH(''), ROOT ('company')
    )

SET @xml.modify('insert sql:variable("@period") as first into (/company)[1]')

SELECT @xml
于 2012-08-23T07:50:09.670 回答
1

您可以将users/person元素的创建嵌套在子选择中,然后围绕它创建外部 XML:

declare @Person table (Name varchar(10))
insert into @Person values ('Bob'),('Harry')

SELECT
'2012' 'period',
(SELECT p.Name 'users/person'
FROM @Person p
FOR XML PATH(''), TYPE
)
FOR XML PATH(''), ROOT ('company')
于 2012-08-23T08:04:07.337 回答
0

您可以随意使用显式模式来塑造它:

CREATE TABLE #person (
    name VARCHAR(10)
)

INSERT #person VALUES ('One')
INSERT #person VALUES ('Two')
INSERT #person VALUES ('Three')
INSERT #person VALUES ('Four')
INSERT #person VALUES ('Five')

SELECT
    1 AS Tag,
    NULL AS Parent,
    '2012' AS [company!1!period!ELEMENT],
    NULL AS [users!2!person!ELEMENT]
FROM
    (SELECT 1 AS fake) AS data
UNION ALL
SELECT
    2 AS Tag,
    1 AS Parent,
    '2012',
    P.name
FROM
    #person P
FOR XML EXPLICIT
于 2012-08-23T07:54:41.683 回答