create table A1( id int, classId char(2), name char(2) ) insert into A1 values (1,1,‘A1‘) insert into A1 values (1,2,‘A2‘) insert into A1 values (2,2,‘A3‘) create table B1( id int, classId char(2), name char(2) ) insert into B1 values (1,1,‘B1‘) insert into B1 values (1,2,‘B2‘) insert into B1 values (2,null,‘B3‘) select A1.id Aid,A1.classId AClassId,A1.name A1name,B1.* into #aa from A1 inner join B1 on A1.id = B1.id and A1.classId = B1.classId select * from #aa union select * from A1 inner join B1 on A1.id = B1.id and not exists(select * from #aa a where A1.id =a.Aid and A1.classId = a.AClassId ) drop table #aa drop table A1 drop table B1