带连接的 SQL 合并语句

问题描述

我正在尝试使用合并语句进行更新插入操作。我想做一些类似下面的事情,我将目标表和源表都加入到 Student 表中,以获得仅存在于 student 表中的唯一键。请记住,我不能加入 StudentID。我的代码中可能有重复。我需要加入 schoolID 以确保唯一性。

Merge into GuardianTo gto inner join StudentTo sto on gto.fkStudentId = sto.StudentID
Using (Select * from GuardianFrom gfrom inner join StudentFrom sfrom on gfrom.fkStudentId = sfrom.StudentID) from
ON gto.guardianId = from.guardianId and sto.SchoolID = from.SchoolID
When....

我需要将目标 GuardianTo 表和 studentTo 表连接起来以获取 SchoolID 的唯一键。并将此 ID 与 From 表匹配。我知道这可以在单独的插入和更新语句(而不是合并)中完成,但是有没有办法使用合并语句执行上述操作?

解决方法

如果您使用的是 MSSQL,您可以像下面的代码一样进行合并。您需要提供要从源查询中使用的列名列表,然后在目标表 (GuardianTo) 中更新/插入您需要的列。

Merge into GuardianTo gto 
Using (Select * from GuardianFrom gfrom inner join StudentFrom sfrom on gfrom.fkStudentId = sfrom.StudentID ) AS source (<column names in GuardianFrom,Studentfrom go here> )
ON (gto.guardianId = source.guardianId and gto.SchoolID = source.SchoolID)        
WHEN MATCHED THEN          
UPDATE SET <column in GuardianTo>= source.<column from source above> /* add any additional columns to update here*/
WHEN NOT MATCHED THEN            
INSERT (guardianId,SchoolID,StudentID /* add any additional columns to insert here*/)            
VALUES (source.guardianId,source.SchoolID,source.StudentID /* add any additional columns from the source to insert here*/);