欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

mssql 两表合并sql语句

程序员文章站 2023-11-04 22:36:28
一、问题 学生表:            &nbs...

一、问题

学生表:                                               课程表:

 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