---
title: "(转)SQL复制数据表 （select * into 与 insert into）"
author: "strayly"
date: "2017-08-25T13:48:24Z"
tags: []
categories: ["数据库"]
slug: "sql-select-into-insert-into"
draft: false
lastmod: "2017-08-25T13:48:24Z"
id: 2391093
url: "https://strayly.iteye.com/blog/2391093"
---

select * into 目标表名 from 源表名

insert into 目标表名(fld1, fld2) select fld1, 5 from 源表名

以上两句都是将 源表 的数据插入到 目标表，但两句又有区别的：

第一句（select into from）要求目标表不存在，因为在插入时会自动创建。 
第二句（insert into select from）要求目标表存在，由于目标表已经存在，所以我们除了插入源表的字段外，还可以插入常量，如例中的：5。



1:复制表结构及数据到新表

select * into 目的数据库名.dbo.目的表名 from 原表名

select * into my0735home.dbo.infoMianTest from infoMian

2:备份表的一部分列（不写*而写出列的列表）

select 列名1,列名2,列名3 into 目的数据库名.dbo.目的表名 from 原表名

select id,title,mtype,stype,author,tel,nr into infoMianTest2 from infomian

3:备份表的一部分行（加WHERE条件）

select * into 目的数据库名.dbo.目的表名 from 原表名 where id<10

select * into infomiantest2 from infomian where id<10

4:备份表的一部分列（不写*而写出列的列表）和一部分行（加WHERE条件）

select 列名1,列名2,列名3 into 目的数据库名.dbo.目的表名 from 原表名 where  id<10

5:只复制表的结构：如：SELECT * INTO t1 FROM titles WHERE 1=2

6:查询结果来源于多个表：如：

SELECT title_id,title,pub_name INTO t3

FROM titles t INNER JOIN publishers p

ON t.pub_id=p.pub_id