Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL Server : manipulating complex xml into tables
    primarykey
    data
    text
    <p>I have some XML which I need to insert into two database tables. The second table (<code>TblSales</code>) must contain the PK of the first (<code>TblDetails.Id</code>). </p> <p>I can insert the data into these tables using XQuery, but I cannot think of a good way to get the PK of <code>TblDetails</code> into FK (<code>DetailsId</code>) of <code>TblSales</code>?</p> <p>I am using SQL Server 2005.</p> <pre><code>DECLARE @xml XML SET @xml = N'&lt;Details&gt; &lt;Detail&gt; &lt;Sub&gt;SubjectName 1&lt;/Sub&gt; &lt;Data&gt;DataName 1&lt;/Data&gt; &lt;Sales&gt; &lt;Sale&gt; &lt;Name&gt;Name 1&lt;/Name&gt; &lt;/Sale&gt; &lt;Sale&gt; &lt;Name&gt;Name 11&lt;/Name&gt; &lt;/Sale&gt; &lt;Sale&gt; &lt;Name&gt;Name 111&lt;/Name&gt; &lt;/Sale&gt; &lt;/Sales&gt; &lt;/Detail&gt; &lt;Detail&gt; &lt;Sub&gt;SubjectName 2&lt;/Sub&gt; &lt;Data&gt;DataName 2&lt;/Data&gt; &lt;Sales&gt; &lt;Sale&gt; &lt;Name&gt;Name 2&lt;/Name&gt; &lt;/Sale&gt; &lt;Sale&gt; &lt;Name&gt;Name 22&lt;/Name&gt; &lt;/Sale&gt; &lt;Sale&gt; &lt;Name&gt;Name 222&lt;/Name&gt; &lt;/Sale&gt; &lt;/Sales&gt; &lt;/Detail&gt; &lt;/Details&gt;' -- Details IF object_id('TblDetails') is not null drop table TblDetails create table TblDetails ( Id int identity not null primary key, Sub nvarchar(max), Data nvarchar(max)) INSERT INTO TblDetails ( Sub, Data ) SELECT ParamValues.Detail.value('(Sub)[1]','NVARCHAR(MAX)') AS [Sub], ParamValues.Detail.value('(Data)[1]','NVARCHAR(MAX)') AS [Data] FROM @xml.nodes('/Details/Detail') AS ParamValues(Detail) -- Sales IF object_id('TblSales') is not null drop table TblSales create table TblSales ( Id int identity not null primary key, Name nvarchar(max), DetailsId int) -- FK to TblDetails.Id PK INSERT INTO TblSales ( Name, DetailsId ) SELECT ParamValues.Sale.value('(Name)[1]','NVARCHAR(MAX)') AS [Name], 1 --Need to get the PK of the newly added row in TblDetails FROM @xml.nodes('/Details/Detail/Sales/Sale') AS ParamValues(Sale) select * from TblDetails select * from TblSales </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload