3

我之前问过一个非常相似的问题,但是现在我需要相同的结果但输入不同。

示例代码:

CREATE TABLE #Temp (
    [@name] VARCHAR(200),
    [Value] VARCHAR(200)
)

INSERT INTO #Temp ([@name], [Value]) 
SELECT 'Fruit', 'Apple' UNION
SELECT 'Fruit', 'Orange' UNION
SELECT 'Fruit', 'Grape'

选择语句

SELECT
    [@name],
    [Value]
FROM #Temp
FOR XML PATH ('Produce'), ROOT('ProduceMaster'), TYPE

结果

<ProduceMaster>
  <Produce name="Fruit">
    <Value>Apple</Value>
  </Produce>
  <Produce name="Fruit">
    <Value>Grape</Value>
  </Produce>
  <Produce name="Fruit">
    <Value>Orange</Value>
  </Produce>
</ProduceMaster>

期望的结果

<ProduceMaster>
  <Produce name="Fruit">
    <Value>Apple</Value>
    <Value>Grape</Value>
    <Value>Orange</Value>
  </Produce>
</ProduceMaster>
4

1 回答 1

5
CREATE TABLE #Temp (
    [@name] VARCHAR(200),
    [Value] VARCHAR(200)
)

INSERT INTO #Temp ([@name], [Value]) 
SELECT 'Fruit', 'Apple' UNION
SELECT 'Fruit', 'Orange' UNION
SELECT 'Fruit', 'Grape' UNION
SELECT 'Building', 'house'


Select  [@Name],
(
SELECT    
    [Value]
FROM #Temp t2
where t2.[@Name] = t1.[@Name]
FOR XML  PATH (''), TYPE
) FROM #Temp t1 GROUP by [@Name]
FOR XML PATH ('Produce'), ROOT('ProduceMaster'), TYPE
于 2013-07-19T20:26:16.970 回答