2010-08-05 5 views
0

Mes données ressemble ci-dessous:Insérer des données XML dans la table 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> 

Mon code SQL ressemble à ceci:

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)    
     ) 

Quand j'avoir plusieurs produits/addons, tous les addons sont insertion avec le dernier @OrderItemID ... Je ne suis pas sûr de savoir comment travailler dans mon SQL qui insère l'addon dans la boucle qui itère à travers les nœuds du produit.

Quelqu'un pourrait-il me diriger dans la bonne direction?

merci à l'avance!

Répondre

0

Je pense,

Vous devez insérer des enregistrements dans la boucle pour obtenir SCOPE_IDENTITY.

Mettez d'abord Order.Items Datain table temporaire, puis en boucle sur pour insérer dans la table Order.Items.

Voici l'idée - Pas de code de travail.

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 

Je l'ai vérifié et en boucle vous pouvez obtenir le 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

Pas vraiment besoin d'utiliser des tables temporaires. – TheGeekYouNeed

Questions connexes