mssql 两表合并sql语句

时间:2022-03-29 09:36:23

一、问题

学生表:                                               课程表:

 id   姓名 课程号(外键)                        课程号,课程名

 '1', 'xix',  1                                              1,' 语文'
 '2', 'cic',  2                                               2, '数学'
 '3', 'ddi', 4                                               3,  '英语'

将学生表、课程表合成一个新表  destTb:

id  姓名  课程号 课程名

1   xix    1    语文
2   cic    2     数学
3   ddi  NULL NULL
NULL NULL 3 英语

二、建立测试数据

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,'数学'
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

三、合并插入

--目标表destTb不存在  ,结果集作为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

--如果目标表destTb已经存在

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