1

i want output

<CustomerName>
<Customer id='1'>
<Name>xyz</Name>
</Customer>
<Customer id='2'>
<Name>Abc</Name>
</Customer>
</CustomerName>

for this output i wrote SP

SELECT
          '' AS [CustomerName],      
          (SELECT 
          Name[Customer/Name]
 FOR XML PATH(''), TYPE) AS[CustomerName/Customer]
          FOR XML PATH('')

not able to add Id attribute, please help me

4
  • It looks like part of your SP is missing - can you show the whole thing? Also, what does your data look like? Commented Apr 25, 2016 at 11:27
  • @bukko SP is complete..my data look like <CustomerName> <Customer> <Name>xyz</Name> </Customer> <Customer> <Name>Abc</Name> </Customer> </CustomerName> Commented Apr 25, 2016 at 11:32
  • SP's begin with CREATE PROCEDURE. Also, I meant your input data i.e. tables, not your output XML. Commented Apr 25, 2016 at 11:34
  • @bukko Create Procedure GetXML ID BIGINT AS BEGIN SELECT '' AS [CustomerName], (SELECT Name[Customer/Name] FROM Customer where CusId=ID FOR XML PATH(''), TYPE) AS[CustomerName/Customer] FOR XML PATH('') END This is full SP Commented Apr 25, 2016 at 11:35

2 Answers 2

1

Try this:

DECLARE @tblCust TABLE(id INT, CustomerName VARCHAR(100));
INSERT INTO @tblCust VALUES
 (1,'xyz')
,(2,'Abc');

SELECT id AS [@id]
      ,CustomerName AS [Name]
FROM @tblCust  
FOR XML PATH('Customer'),ROOT('CustomerName')

This is the result

<CustomerName>
  <Customer id="1">
    <Name>xyz</Name>
  </Customer>
  <Customer id="2">
    <Name>Abc</Name>
  </Customer>
</CustomerName>
Sign up to request clarification or add additional context in comments.

Comments

1
SELECT [@id] = t.id, [Name] = t.name
FROM (
    VALUES (1, 'name'), (2, 'name2')
) t (id, name)
FOR XML PATH('Customer'), ROOT('CustomerName')

1 Comment

Ha, gotcha! Next time you'll win again :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.