2010-08-05 57 views
0

我的数据看起来象下面这样:插入XML数据转换成SQL Server表

<products> 
    <product ProductID="1" Price="79.99" Weight="30.00" Quantity="1"> 
     <addon ProductAddonID="0" ControlTypeID="9" Price="25.00" Weight="0.00" Quantity="1" Name="yyy" Data="ASD" />  
     <addon ProductAddonID="89" ControlTypeID="0" Price="15.00" Weight="4.00" Quantity="1" Name="xxx" Data="" /> 
    </product> 
</products> 

我的SQL代码如下所示:

INSERT INTO [Order].Items(OrderID, ProductID, Price, Weight, Quantity) 
SELECT @OrderID, ProductID, Price, Weight, Quantity 
FROM OPENXML (@XmlHandle, '/products/product',1) 
      WITH (ProductID INT '@ProductID', 
         Price DECIMAL(6,2) '@Price', 
         Weight DECIMAL(6,2) '@Weight', 
         Quantity INT '@Quantity') 

SET @OrderItemId = SCOPE_IDENTITY() 



INSERT INTO [Order].Addons(OrderItemID, ProductAddonID, ControlTypeID, Price, Weight, Quantity, [Name], DATA) 
SELECT @OrderItemId, ProductAddonID, ControlTypeID, Price, Weight, Quantity, [Name], [Data] 
FROM OPENXML(@XMLHandle, '/products/product/addon',1) 
WITH (
     ProductAddonID INT, 
     ControlTypeID INT, 
     Price DECIMAL(6,2), 
     Weight DECIMAL(6,2), 
     Quantity INT, 
     [Name] NVARCHAR(500), 
     [Data] NVARCHAR(max)    
     ) 

当我有多个产品/插件,所有的插件都插入最新的@OrderItemID ......我不知道如何在我的SQL中工作,将插件插入循环遍历产品节点的循环中。

任何人都可以指向正确的方向吗?

在此先感谢!

回答

0

我认为,

你需要插入在回路记录得到SCOPE_IDENTITY。

首先把Order.Items datain临时表,然后在它上面循环插入到Order.Items表中。

以下是想法 - 不工作的代码。

DECLARE @count INT 
DECLARE @id INT 

SET @count = 1 
SET @id = totalNumberOfRecordsInTempTable -- Get records from xml to temp table first 


WHILE @count <= @id 
BEGIN 
    INSERT INTO YourTable (Column1, Column2, ...) 
    SELECT Column1, Column2, ... FROM SourceTable WHERE Id = @count 

    SET @count = @count + 1 

    SET @OrderItemId = SCOPE_IDENTITY() 

    INSERT INTO Order.AddOns 

END 

我已经检查,并在循环中,您可以得到SCOPE_IDENTITY。

declare @table table 
(
    id int, 
    quanity int 
) 

insert into @table select 1, 10 
insert into @table select 2, 20 
insert into @table select 3, 30 
insert into @table select 4, 40 

declare @table2 table 
(
    orderid int identity(1, 1), 
    quanity int 
) 

declare @id int 
select @id = max(id) from @table 

while @id > 0 
begin 
    insert into @table2 (quanity) 
    select quanity from @table where id = @id 

    set @id = @id - 1 

    select SCOPE_IDENTITY() 
end 
+0

不是真的想使用临时表。 – TheGeekYouNeed 2010-08-05 18:29:46