Thursday, April 2, 2009

Fetch XML format Data in SQL server

Hi ,
let's to discus how we ll read XML data in sqlserver .

DECLARE @docHandle int, @OID int,@order nvarchar(4000)
set @order='
<?xml version="1.0"? >
<Order >
<CustomerID > ALFKI </CustomerID >
<EmployeeID > 3 </EmployeeID >
<OrderDate>07/3/2004 < OrderDate >
<RequiredDate>07/4/2004 </RequiredDate >
<ShippedDate>15/3/2004 < /ShippedDate >
<OrderDetails ProductID="2" UnitPrice="15"
Quantity="5" Discount="0.15" > < /OrderDetails>
<OrderDetails ProductID="4" UnitPrice="22"
Quantity="7" Discount="0.21" > </OrderDetails >
<OrderDetails ProductID="10" UnitPrice="31"
Quantity="3" Discount="0.15" > </OrderDetails >
</Order>'


EXEC sp_xml_preparedocument @docHandle OUTPUT, @order
SELECT CustomerID, EmployeeID, OrderDate, RequiredDate
FROM Openxml( @docHandle, '/Order', 3)
WITH ( CustomerID nchar(5),
EmployeeID int, OrderDate datetime, RequiredDate datetime )
SELECT @OID AS [PO ID], ProductID, UnitPrice, Quantity, Discount
FROM OpenXml( @docHandle, '/Order/OrderDetails', 1) WITH
( ProductID int, UnitPrice money, Quantity smallint, Discount real )

*************************************************************
Procedure
*************************************************************
CREATE PROCEDURE xmlOrderInsert @order ntext
AS
DECLARE @docHandle int, @OID int
EXEC sp_xml_preparedocument @docHandle OUTPUT, @order
BEGIN TRANSACTION
INSERT INTO Orders( CustomerID, EmployeeID, OrderDate, RequiredDate )
SELECT CustomerID, EmployeeID, OrderDate, RequiredDate
FROM Openxml( @docHandle, '/Order', 3)
WITH ( CustomerID nchar(5),
EmployeeID int, OrderDate datetime, RequiredDate datetime )
IF @@ERROR<>0 BEGIN ROLLBACK TRANSACTION RETURN -100 END
SET @OID = SCOPE_IDENTITY()
INSERT INTO [Order Details] ( OrderID, ProductID, UnitPrice, Quantity, Discount )
SELECT @OID AS [PO ID], ProductID, UnitPrice, Quantity, Discount
FROM OpenXml( @docHandle, '/Order/OrderDetails', 1) WITH
( ProductID int, UnitPrice money, Quantity smallint, Discount real )
IF @@ERROR<>0 BEGIN ROLLBACK TRANSACTION RETURN -101 END
COMMIT TRANSACTION
EXEC sp_xml_removedocument @docHandle SELECT @OID AS [Order ID]
GO

1 comment:

Unknown said...

Thanks a lot. It's help me to manage 12000000 records from XML file to DB.
But the Problem is to matching new data with the existing 1 Crore data.....

Hope you will help me the best way to match new records with existing 1 Crore.

Enjoy..