sql-server - 使用在基于集合的插入期间创建的 ID 更新现有临时表

标签 sql-server xml output

我提取了一些 XML进入一个临时表如下:

declare @INT_ParticipantID INT = 1
declare @XML_Results XML = '
<roots>
  <root>
    <ID />
    <ResultDateTime>2016-08-16T13:58:21.484Z</ResultDateTime>
    <Test>
      <ID>5</ID>
      <ParticipantID>0</ParticipantID>
      <Instrument />
      <ControlSet />
      <Assay />
      <CreationDate>0001-01-01T00:00:00Z</CreationDate>
      <StartDate>0001-01-01T00:00:00Z</StartDate>
      <EndDate>0001-01-01T00:00:00Z</EndDate>
      <Closed>false</Closed>
      <SlideGenNumber>0</SlideGenNumber>
    </Test>
    <EnteredByInitials />
    <ControlSetLots />
    <LotResult1 />
    <LotResult2 />
    <LotResult3 />
    <LotResults>
      <ID>13</ID>
      <LotNumber />
      <LotName />
      <ExpiryDate>0001-01-01T00:00:00Z</ExpiryDate>
      <Result>
        <ID />
        <Count>1</Count>
        <Mean>2</Mean>
        <SD>3</SD>
      </Result>
      <ParticipantID>0</ParticipantID>
      <ApprovalStatus>false</ApprovalStatus>
      <LotAnalytes />
      <LotInstruments />
      <TestDetails />
    </LotResults>
    <LotResults>
      <ID>14</ID>
      <LotNumber />
      <LotName />
      <ExpiryDate>0001-01-01T00:00:00Z</ExpiryDate>
      <Result>
        <ID />
        <Count>4</Count>
        <Mean>5</Mean>
        <SD>6</SD>
      </Result>
      <ParticipantID>0</ParticipantID>
      <ApprovalStatus>false</ApprovalStatus>
      <LotAnalytes />
      <LotInstruments />
      <TestDetails />
    </LotResults>
    <LotResults>
      <ID>0</ID>
      <LotNumber />
      <LotName />
      <ExpiryDate>0001-01-01T00:00:00Z</ExpiryDate>
      <Result>
        <ID />
        <Count>1</Count>
        <Mean>0</Mean>
        <SD>0</SD>
      </Result>
      <ParticipantID>0</ParticipantID>
      <ApprovalStatus>false</ApprovalStatus>
      <LotAnalytes />
      <LotInstruments />
      <TestDetails />
    </LotResults>
    <StandardComment>
      <ID>1</ID>
      <EnteredBy />
      <Description />
    </StandardComment>
    <ReviewComment>
      <ID />
      <EnteredBy />
      <Description />
    </ReviewComment>
  </root>
</roots>
'

  SELECT r.value('ID[1]','int') AS Transaction_ID
        ,r.value('ResultDateTime[1]', 'datetime') AS Transaction_DateTime
        ,r.value('(Test/ID)[1]', 'int') AS QCTest_ID
        ,lr.value('ID[1]','int') AS Lot_ID
        ,lr.value('(Result/Count)[1]','int') AS Result_Count
        ,lr.value('(Result/Mean)[1]','decimal(18, 8)') AS Result_Mean
        ,lr.value('(Result/SD)[1]','decimal(18, 8)') AS Result_SD
        ,r.value('(StandardComment/ID)[1]','int') AS StandardComment_ID 
        ,r.value('(ReviewComment/ID)[1]','int') AS ReviewComment_ID 
    INTO #tempRawXML
    FROM @XML_Results.nodes('/roots/root') AS A(r)
   CROSS 
   APPLY r.nodes('LotResults') AS B(lr)  

这使我返回以下结果集:

Result set returned when extracting XML

我需要将提取的结果插入到两个表中——一个是映射表,另一个是由Lot_ID决定的。通过 XML 发送的字段.

我需要实现的是 INSERT到映射表中,然后提取新生成的主键字段(这是一个 IDENTITY )和 INSERT它与剩余的结果数据一起进入相关表格。

我认为最有效的方法是 UPDATE现有Transaction_ID #tempRawXML 中的列表与 OUTPUT第一个 INSERT手术。有什么办法可以做到这一点?到目前为止,我有以下内容 - 它在 #tempRawXML 中创建了一个新行表与相关Transaction_ID :

INSERT 
     INTO dbo.Result_Transaction_Mapping
        (
            fk_participant_id,
            fk_test_id,
            result_date_time,
            fk_comment_id,
            fk_review_comment_id
        )
   OUTPUT INSERTED.pk_id 
     INTO #tempRawXML(Transaction_ID)
   SELECT @INT_ParticipantID,
          QCTest_ID,
          Transaction_DateTime,
          StandardComment_ID,
          ReviewComment_ID
     FROM #tempRawXML

How the temp table looks following the insert

有没有办法修改上面的内容,而不是插入仅包含生成的 Transaction_ID 的新行? , 它会更新 #tempRawXML 中的现有行?

最佳答案

在研究了UPDATE 原始 tempRawXML 表的方法后 - 无济于事 - 我有一个解决初始问题的组合:

使用的 XML:

declare @XML_Results XML = '
<roots>
  <root>
    <ID>-2</ID>
    <ResultDateTime>2016-08-24T10:44:22.829Z</ResultDateTime>
    <Test>
      <ID>5</ID>
      <ParticipantID>0</ParticipantID>
      <Instrument />
      <ControlSet />
      <Assay />
      <CreationDate>0001-01-01T00:00:00Z</CreationDate>
      <StartDate>0001-01-01T00:00:00Z</StartDate>
      <EndDate>0001-01-01T00:00:00Z</EndDate>
      <Closed>false</Closed>
      <SlideGenNumber>0</SlideGenNumber>
    </Test>
    <EnteredByInitials />
    <ControlSetLots />        
    <LotResults>
      <ID>13</ID>
      <LotNumber />
      <LotName />
      <ExpiryDate>0001-01-01T00:00:00Z</ExpiryDate>
      <Result>
        <ID />
        <Count>5</Count>
        <Mean>6</Mean>
        <SD>7</SD>
      </Result>
      <ParticipantID>0</ParticipantID>
      <ApprovalStatus>false</ApprovalStatus>
      <LotAnalytes />
      <LotInstruments />
      <TestDetails />
    </LotResults>
    <LotResults>
      <ID>14</ID>
      <LotNumber />
      <LotName />
      <ExpiryDate>0001-01-01T00:00:00Z</ExpiryDate>
      <Result>
        <ID />
        <Count>1</Count>
        <Mean>0</Mean>
        <SD>0</SD>
      </Result>
      <ParticipantID>0</ParticipantID>
      <ApprovalStatus>false</ApprovalStatus>
      <LotAnalytes />
      <LotInstruments />
      <TestDetails />
    </LotResults>
    <LotResults>
      <ID>0</ID>
      <LotNumber />
      <LotName />
      <ExpiryDate>0001-01-01T00:00:00Z</ExpiryDate>
      <Result>
        <ID />
        <Count>1</Count>
        <Mean>0</Mean>
        <SD>0</SD>
      </Result>
      <ParticipantID>0</ParticipantID>
      <ApprovalStatus>false</ApprovalStatus>
      <LotAnalytes />
      <LotInstruments />
      <TestDetails />
    </LotResults>
    <StandardComment>
      <ID />
      <EnteredBy />
      <Description />
    </StandardComment>
    <ReviewComment>
      <ID />
      <EnteredBy />
      <Description />
    </ReviewComment>
  </root>
  <root>
    <ID>-1</ID>
    <ResultDateTime>2016-08-24T10:44:22.829Z</ResultDateTime>
    <Test>
      <ID>5</ID>
      <ParticipantID>0</ParticipantID>
      <Instrument />
      <ControlSet />
      <Assay />
      <CreationDate>0001-01-01T00:00:00Z</CreationDate>
      <StartDate>0001-01-01T00:00:00Z</StartDate>
      <EndDate>0001-01-01T00:00:00Z</EndDate>
      <Closed>false</Closed>
      <SlideGenNumber>0</SlideGenNumber>
    </Test>
    <EnteredByInitials />
    <ControlSetLots />        
    <LotResults>
      <ID>13</ID>
      <LotNumber />
      <LotName />
      <ExpiryDate>0001-01-01T00:00:00Z</ExpiryDate>
      <Result>
        <ID />
        <Count>1</Count>
        <Mean>0</Mean>
        <SD>0</SD>
      </Result>
      <ParticipantID>0</ParticipantID>
      <ApprovalStatus>false</ApprovalStatus>
      <LotAnalytes />
      <LotInstruments />
      <TestDetails />
    </LotResults>
    <LotResults>
      <ID>14</ID>
      <LotNumber />
      <LotName />
      <ExpiryDate>0001-01-01T00:00:00Z</ExpiryDate>
      <Result>
        <ID />
        <Count>1</Count>
        <Mean>2</Mean>
        <SD>3</SD>
      </Result>
      <ParticipantID>0</ParticipantID>
      <ApprovalStatus>false</ApprovalStatus>
      <LotAnalytes />
      <LotInstruments />
      <TestDetails />
    </LotResults>
    <LotResults>
      <ID>0</ID>
      <LotNumber />
      <LotName />
      <ExpiryDate>0001-01-01T00:00:00Z</ExpiryDate>
      <Result>
        <ID />
        <Count>1</Count>
        <Mean>0</Mean>
        <SD>0</SD>
      </Result>
      <ParticipantID>0</ParticipantID>
      <ApprovalStatus>false</ApprovalStatus>
      <LotAnalytes />
      <LotInstruments />
      <TestDetails />
    </LotResults>
    <StandardComment>
      <ID />
      <EnteredBy />
      <Description />
    </StandardComment>
    <ReviewComment>
      <ID />
      <EnteredBy />
      <Description />
    </ReviewComment>
  </root>
</roots>
'

1) 用于将 UI“映射”到 IDENTITY 生成的 ID 的附加临时表(感谢@Pawel 的建议让我走上正轨)。 注意:我从 UI 为 Old_ID 字段发送一个增量负值,以确保这些值永远不会与现有的 IDENTITY 匹配。

  -- Hold mappings between old and processed IDs
  -- Used when inserting into relevant lot tables following initial top level transaction insert
  CREATE 
   TABLE #Processed_Transactions 
       (
        Old_ID INT, -- ID supplied by UI (using a negative number to ensure no conflict with IDs from Result_Transaction_Mapping table)
        ProcessedTransaction_ID INT -- ID generated during initial insert into Result_Transaction_Mapping table
       )

2) MERGE 结合 OUTPUT 将初始事务插入并跟踪 Old_ID/ProcessedTransaction_ID映射临时表中的字段。 此时出现 1=0 场景以确保始终触发 INSERT。这似乎有点不确定,但似乎被广泛使用。

Example from another question using MERGE instead of INSERT

   -- Function to insert the top level Result Transaction
   -- Required to populate OUTPUT variable in Processed_Transactions temporary table
   MERGE dbo.Result_Transaction_Mapping AS RTM 
   USING 
       (
          -- Extracts distinct UI assigned IDs and column information
          SELECT DISTINCT Assigned_ID, 
                 MAX(Transaction_DateTime) AS Transaction_DateTime, 
                 MAX(QCTest_ID) as QCTest_ID, 
                 MAX(StandardComment_ID) AS StandardComment_ID, 
                 MAX(ReviewComment_ID) AS ReviewComment_ID, 
                 MAX(Result_Count) AS Result_Count, 
                 MAX(Result_Mean) AS Result_Mean, 
                 MAX(Result_SD) AS Result_SD 
            FROM #tempRawXML 
           GROUP 
              BY Assigned_ID
      ) AS TR
     -- Create 1 = 0 scenario to ensure the IDs never match up to what currently exists in the Result_Transaction_Mapping table
     ON TR.Assigned_ID = RTM.pk_id
   WHEN NOT MATCHED 
    -- Ensure at least one of the transaction result columns contain a value
    -- This will also be verified on the UI
    AND TR.Result_Count > 0
    AND TR.Result_Mean > 0.0
    AND TR.Result_SD > 0.0
   THEN
 INSERT 
      (
        fk_participant_id, 
        fk_test_id, 
        result_date_time, 
        fk_comment_id, 
        fk_review_comment_id
      )
 VALUES 
      (
        @INT_ParticipantID, 
        TR.QCTest_ID, 
        TR.Transaction_DateTime, 
        TR.StandardComment_ID, 
        TR.ReviewComment_ID
      )   
 -- Following insert of a result, populate the INSERTED primary key field into the mappings table
 OUTPUT TR.Assigned_ID, 
        INSERTED.pk_id
   INTO #Processed_Transactions 
      (
        Old_ID, 
        ProcessedTransaction_ID
      );

在此之后,我现在有了一组数据集,可用于插入到相关的 Lot 表中。

#tempRawXML

Temp Raw XML table

ID 映射 与 UI 负映射和 IDENTITY 表生成的 ID

ID Mappings table

这让我陷入了另一个困境 - 使用 CURSORS 并因此冒险回到“程序方法的黑暗领域”(@Shnugo in a previous question 强烈建议不要这样做,他我想现在正在“诅咒”我的名字。

在成功执行顶级结果事务 INSERT 并使用上面的原始 XML 和生成的 ID 之后,我需要将剩余的“特定于结果”的信息插入到它们各自的表中,其中的名称尚未根据结果 LotID 确定。因此,我设置了以下程序化、基于集合的动态 SQL 组合(如果有的话)来完成此任务:

 -- recursively access each associated Lot table based on associated Lot ID's
 DECLARE @LotNumber NVARCHAR(20), @LotID INT 
 -- Querystring to hold all set update calls
 DECLARE @ResultQueryString NVARCHAR(MAX) = ''
 DECLARE Lot_Cursor
  CURSOR FAST_FORWARD
     FOR
      -- Select the lot numbers based on the available IDs
      SELECT 
    DISTINCT L.pk_id AS LotID,
             L.number AS LotNumber
        FROM dbo.Lot L
        LEFT
        JOIN #tempRawXML TR 
          ON TR.Lot_ID = L.pk_id
       WHERE L.pk_id IN (TR.Lot_ID)

        OPEN Lot_Cursor

       FETCH 
        NEXT 
        FROM Lot_Cursor
        INTO @LotID, @LotNumber

       WHILE @@fetch_status = 0
       BEGIN
         SET @ResultQueryString +=
           N'  MERGE dbo.[' + @LotNumber + '] AS L
               USING 
                    (
                        SELECT PT.ProcessedTransaction_ID,
                               TR.Result_ID,
                               TR.Result_Count, 
                               TR.Result_Mean, 
                               TR.Result_SD 
                          FROM #tempRawXML TR
                          JOIN #Processed_Transactions PT
                            ON PT.Old_ID = TR.Assigned_ID
                         WHERE TR.Lot_ID = '+ CAST(@LotID AS NVARCHAR(20)) +'
                    ) R
                 ON R.Result_ID = L.pk_id   
               WHEN NOT MATCHED     
                AND R.Result_Count > 0
                AND R.Result_Mean > 0.0
                AND R.Result_SD > 0.0       
               THEN
             INSERT
                  (
                     fk_result_transaction_mapping_id,
                     count,
                     mean,
                     standard_deviation,
                     result_status              
                  )
             VALUES
                  (
                     R.ProcessedTransaction_ID,
                     R.Result_Count,
                     R.Result_Mean,
                     R.Result_SD,
                     1
                  ); '            

       FETCH
        NEXT
        FROM Lot_Cursor
        INTO @LotID, @LotNumber

         END
       CLOSE Lot_Cursor
  DEALLOCATE Lot_Cursor        

        -- @Processed_Transactions temp table variable must be declared when executing dynamic sql
        --EXEC sp_executesql @ResultQueryString, N'@Processed_Transactions MyTable READONLY', @Processed_Transactions=@Processed_Transactions
        EXEC (@ResultQueryString)

我的后续问题 - 这是对 CURSORS 的可接受使用吗(记住最多只能有 6 次迭代)?此外,在这种情况下有没有办法避免使用 CURSOR

关于sql-server - 使用在基于集合的插入期间创建的 ID 更新现有临时表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39099685/

相关文章:

具有不同日期和时间字段的日期/时间之间的 SQL 查询

sql - 添加自动增量额外列以查看 SQL Server 表中不存在的列

sql-server - T-SQL 中的位翻转操作

java - android中表单程序生成的布局到XML布局

c - 在不排序的情况下删除数组中的重复元素 - 错误输出

保存在字段中的 SQL 函数 - 如何执行 DATEADD()?

java - Java 应用程序的 XML 配置文件中的 ${some.thing} 是什么

android - XML 反序列化期间内存不足

formatting - 如何在 Maxima 中格式化 Fortran 输出

java - 将换行符写入输出文本文件