ehsan
ehsan

Reputation: 787

adding attribute to the same tag in xml in sql server

i have a table named 'Words' in sql server with these columns: Id, Type, Word

i want to write a query to generate a xml like this

<Words>
  <Word Id="1" Type="8">some text1</Word>
  <Word Id="2" Type="4">some text2</Word>
  <Word Id="3" Type="5">some text3</Word>
</Words>

how can i do that?

Upvotes: 1

Views: 209

Answers (1)

Martin Smith
Martin Smith

Reputation: 453897

WITH Words(Id, Type, Word) AS
(
SELECT 1, 8, 'some text1' UNION ALL
SELECT 2, 4, 'some text2' UNION ALL
SELECT 3, 5, 'some text3' 
)
SELECT Id   AS [@Id],
       Type AS [@Type],
       Word AS [text()]
FROM Words
FOR XML PATH('Word'), ROOT('Words')

Upvotes: 3

Related Questions