sql—从另一个表向表中插入行,而不迭代游标

gmxoilav  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(272)

我有下面的表格,机器人和机器人。我想将robot中的datetested字段迁移到相应robot的robottestresult中的datetested字段。

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

对于任何机器人,robottestresult表中最多有一个条目
有些机器人在robottestresult表中会有相应的条目,我可以用一个简单的连接来更新这些值:

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

问题在于robottestresult表中没有条目的机器人。我能想到的唯一方法是使用光标遍历没有rtr条目的每个robot并进行插入,但我觉得必须有一种更有效的方法。
编辑以添加:如果robot中不存在datetested值,则不应插入robottestresult。

m3eecexj

m3eecexj1#

我更喜欢使用 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
    )
9avjhtql

9avjhtql2#

我们也可以使用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);
gg0vcinb

gg0vcinb3#

又快又脏的解决方案。基本上,如果左连接未找到匹配项,则将该值添加到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

相关问题