Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server XML - setting node names from SQL value

Tags:

sql

sql-server

How do I generate node names in a SELECT FOR XML statement?

Say I have the table:

declare @Products table (ID int, Name varchar(100))
insert into @Products (1, 'Balls')
insert into @Products (2, 'Paper')
insert into @Products (3, 'Beer')

I want the following XML output:

<Products>
    <Balls @ID=1/>
    <Paper @ID=2/>
    <Beer @ID=3/>
</Products>

If not possible, can I use SQL Server XML DML to accomplish this?

like image 764
Pål Thingbø Avatar asked Jun 14 '26 07:06

Pål Thingbø


1 Answers

Well, I don't think you can do that with FOR XML PATH commands in straight forward way.

So after thinking a lot i came up with following solution which is something awkward but it works:

DECLARE @Products TABLE (ID int, Name varchar(100))

INSERT INTO @Products (id, name) 
VALUES (1, 'Balls'),
       (2, 'Paper'),
       (3, 'Beer')

SELECT 
    CAST('<' + NAME + ' id="' + CAST(id AS VARCHAR) + '" />' AS XML)
FROM 
    @Products
FOR XML PATH(''), ROOT('Products')

Output:

<Products>
  <Balls id="1" />
  <Paper id="2" />
  <Beer id="3" />
</Products>

AND here is the SQL Fiddle

like image 166
Krishnraj Rana Avatar answered Jun 17 '26 01:06

Krishnraj Rana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!