Simple XML
SELECT TOP 3 ProductID, [Name], ProductNumber,SafetyStockLevel
FROM Production.Product
FOR XML RAW
The output is as below.
<row ProductID="1" Name="Adjustable Race" ProductNumber="AR-5381" SafetyStockLevel="1000" /> <row ProductID="2" Name="Bearing Ball" ProductNumber="BA-8327" SafetyStockLevel="1000" /> <row ProductID="3" Name="BB Ball Bearing" ProductNumber="BE-2349" SafetyStockLevel="800" />
Column Name as Elements
The above XML is good. But I want an XML with the column name as elements. This can be done by using PATH.
SELECT TOP 3 ProductID, [Name], ProductNumber,SafetyStockLevel
FROM Production.Product
FOR XML PATH('Product')
<Products> <ProductID>1</ProductID> <Name>Adjustable Race</Name> <ProductNumber>AR-5381</ProductNumber> <SafetyStockLevel>1000</SafetyStockLevel> </Products> <Products> <ProductID>2</ProductID> <Name>Bearing Ball</Name> <ProductNumber>BA-8327</ProductNumber> <SafetyStockLevel>1000</SafetyStockLevel> </Products> <Products> <ProductID>3</ProductID> <Name>BB Ball Bearing</Name> <ProductNumber>BE-2349</ProductNumber> <SafetyStockLevel>800</SafetyStockLevel> </Products>
The above XML is much better than the XML what we have generated in the previous example. But still there is a problem. This XML is not a well formatted one. There is no root element in the above XML.
The below query will solve our problem.
XML with Root Element
SELECT TOP 5 ProductID, [Name], ProductNumber,SafetyStockLevel
FROM Production.Product
FOR XML PATH('Product'), ROOT('Products')
Here is the XML generated from the above query. Here is the XML with the root element.
<Products> <Product> <ProductID>1</ProductID> <Name>Adjustable Race</Name> <ProductNumber>AR-5381</ProductNumber> <SafetyStockLevel>1000</SafetyStockLevel> </Product> <Product> <ProductID>2</ProductID> <Name>Bearing Ball</Name> <ProductNumber>BA-8327</ProductNumber> <SafetyStockLevel>1000</SafetyStockLevel> </Product> <Product> <ProductID>3</ProductID> <Name>BB Ball Bearing</Name> <ProductNumber>BE-2349</ProductNumber> <SafetyStockLevel>800</SafetyStockLevel> </Product> </Products>
How simple is it to generate an XML from SQL Server 2005? I am keen to explore the enhancements in SQL Server 2008.
0 comments:
Post a Comment