简体   繁体   中英

creating XML in T-SQL with multiple attributes

Would like to ask how to create xml doc in T SQL which looks like this.

<?xml version="1.0" encoding="UTF-8"?>
<root firstAttribute="test" secondAttribute="test" etc...>
   <order firstAttribute="test" secondAttribute="test" etc...></order>
</root>

I don't really know how to insert multiple argumets.

Thanks

use **FOR XML to Convert the table to the XML format **

SELECT TOP 10 *
FROM Customers 
inner join Orders  on Customers.CustomerID= Orders.CustomerID 
FOR XML AUTO  

and add string before

select '<?xml version="1.0" encoding="UTF-8"?>'  + (
SELECT TOP 10 *
FROM Customers 
inner join Orders  on Customers.CustomerID= Orders.CustomerID 
FOR XML AUTO  
) 

This will provide you with the logic you need to create xml from a table "TestTable".

DECLARE @TestTable table (firstAttribute int, secondAttribute varchar(100))

INSERT INTO @TestTable values (1,'Test 1')
INSERT INTO @TestTable values (2,'Test 2')


SELECT '<?xml version="1.0" encoding="UTF-8"?>'  + (
    SELECT 
           firstAttribute,
           secondAttribute     
    FROM   @TestTable
    FOR XML PATH ('root')

)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM