First, the following XML is saved to XML file C:\Products.xml.
<Products>
<Product>
<SKU>1</SKU>
<Desc>Book</Desc>
</Product>
<Product>
<SKU>2</SKU>
<Desc>DVD</Desc>
</Product>
<Product>
<SKU>3</SKU>
<Desc>Video</Desc>
</Product>
</Products>
Next, a table named Products is created to store the XML data.
CREATE TABLE Products(
sku INT PRIMARY KEY,
product_desc VARCHAR(30));
Finally, the following statement will load the XML file, parse the XML elements to columns, and insert into the Products table:
INSERT INTO Products (sku, product_desc)
SELECT X.product.query('SKU').value('.', 'INT'),
X.product.query('Desc').value('.', 'VARCHAR(30)')
FROM (
SELECT CAST(x AS XML)
FROM OPENROWSET(
BULK 'C:\Products.xml',
SINGLE_BLOB) AS T(x)
) AS T(x)
CROSS APPLY x.nodes('Products/Product') AS X(product);
Here are the results:
SELECT sku, product_desc
FROM Products;
/*
Results:
sku product_desc
----------- -------------
1 Book
2 DVD
3 Video
*/

1 comments:
For work with sql files I often use-recovery database sql.On next reasons: tool solved all my problems with sql files quickly and easy.Moreover it was for free and program demonstrated repair data from corrupted databases in the MS SQL Server format (files with the *.mdf extension).
Post a Comment