【问题标题】:Inserting rows into a table from another table without iterating over a cursor将行从另一个表插入到一个表中而不迭代游标
【发布时间】:2020-07-10 03:20:02
【问题描述】:

我有下表,Robot 和 RobotTestResult。我想将 Robot 中的 DateTested 字段迁移到对应 Robot 的 RobotTestResult 中的 DateTested 字段。

Robot         RobotTestResult
--------      ---------------
RobotID       RobotTestID (Identity)
DateTested    RobotID
              DateTested

任何机器人的 RobotTestResult 表中最多有 1 个条目

一些机器人将在 RobotTestResult 表中有相应的条目,我可以通过简单的连接来更新这些值:

UPDATE RTR
SET RTR.DateTested = r.DateTested
FROM [dbo].[RobotTestResult] RTR
JOIN [Robot] r
ON RTR.RobotID = r.RobotID;

问题在于在 RobotTestResult 表中没有条目的机器人。我能想到的唯一方法是使用 Cursor 遍历每个没有 RTR 条目并进行插入的 Robot,但我觉得必须有更有效的方法。

编辑添加:如果 Robot 中不存在 DateTested 值,则不应插入 RobotTestResult。

【问题讨论】:

  • 所以你想为每个还没有的机器人添加一个新的RobotTestResult 记录?
  • 每个机器人的新 RobotTestResult 仅具有 DateTested 值。如果 Robot 中不存在 DateTested 值,则不应采取任何措施。

标签: sql sql-server tsql insert cursor


【解决方案1】:

我更喜欢在这种情况下使用NOT EXISTS,因为它符合问题的逻辑。

INSERT INTO RobotTestResults (RobotID, DatedTest)
    SELECT RobotID, DateTest
    FROM Robot R
    WHERE DateTest IS NOT NULL
    AND NOT EXISTS (
        SELECT 1
        FROM RobotTestRules RTR
        WHERE RTR.RobotID = R.RobotID
    )

【讨论】:

    【解决方案2】:

    我们也可以使用 MERGE 语句来达到同样的效果。我个人喜欢@Dale K 解决方案。但是,将其添加为 TSQL 中的附加选项。

    MERGE [dbo].[RobotTestResult] as tgt
    USING (SELECT * FROM Robot) AS src
    ON tgt.RobotID = src.RobotID AND src.DateTested IS NOT NULL
    WHEN MATCHED THEN
    UPDATE SET DateTested = src.DateTested
    WHEN NOT MATCHED THEN
    INSERT (RobotID, DateTested)
    VALUES (src.RobotID, src.DateTested);
    

    【讨论】:

      【解决方案3】:

      快速而肮脏的解决方案。基本上,如果左连接没有找到匹配项,则将值添加到 RobotTestResults

      INSERT INTO RobotTestResults
      (RobotID,DatedTest)
      SELECT RobotID,DateTest
      FROM Robot r
      LEFT JOIN RobotTestRules rtr on rtr.robotID = r.robitID
      WHERE rtr.robotID is NULL
      

      【讨论】:

        猜你喜欢
        • 2014-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多