mssql 兩表合并sql語句_MsSql

來源:互聯網
上載者:User

一、問題

學生表:                                               課程表:

 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.