一、問題
學(xué)生表: 課程表:
id 姓名 課程號(hào)(外鍵) 課程號(hào),課程名
'1', 'xix', 1 1,' 語文'
'2', 'cic', 2 2, '數(shù)學(xué)'
'3', 'ddi', 4 3, '英語'
將學(xué)生表、課程表合成一個(gè)新表 destTb:
id 姓名 課程號(hào) 課程名
1 xix 1 語文
2 cic 2 數(shù)學(xué)
3 ddi NULL NULL
NULL NULL 3 英語
二、建立測(cè)試數(shù)據(jù)
CREATE TABLE student(id nvarchar(10),name nvarchar(10),cno int)
INSERT student SELECT '1','xix',1
UNION ALL SELECT '2','cic',2
UNION ALL SELECT '3','ddi',4
GO
CREATE TABLE class(cno int,name nvarchar(10))
INSERT class SELECT 1,'語文'
UNION ALL SELECT 2,'數(shù)學(xué)'
UNION ALL SELECT 3,'英語'
GO
select id ,s.name as 姓名,c.cno as cno,c.name as 課程 FROM student as s FULL OUTER JOIN class as c ON s.cno=c.cno
三、合并插入
--目標(biāo)表destTb不存在 ,結(jié)果集作為tmp
select * into destTb from (select id ,s.name as 姓名,c.cno as cno,c.name as 課程 FROM student as s FULL OUTER JOIN class as c ON s.cno=c.cno) as tmp
--如果目標(biāo)表destTb已經(jīng)存在
insert into destTb select id ,s.name as 姓名,c.cno as cno,c.name as 課程 FROM student as s FULL OUTER JOIN class as c ON s.cno=c.cno