Sql Server 复制表

SELECT INTO 和 INSERT INTO SELECT 两种表复制语句 

 1.INSERT INTO SELECT语句

      语句形式为:Insert into Table2(field1,field2,...) select value1,value2,... from Table1

      要求目标表Table2必须存在,由于目标表Table2已经存在,所以我们除了插入源表Table1的字段外,还可以插入常量。示例如下:

 1 --1.创建测试表
 2 
 3     create TABLE Table1
 4 
 5     (
 6 
 7         a varchar(10),
 8 
 9         b varchar(10),
10 
11         c varchar(10),
12 
13         CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED
14 
15         (
16 
17             a ASC
18 
19         )
20 
21     ) ON [PRIMARY]
22 
23 
24 
25     create TABLE Table2
26 
27     (
28 
29         a varchar(10),
30 
31         c varchar(10),
32 
33         d int,
34 
35         CONSTRAINT [PK_Table2] PRIMARY KEY CLUSTERED
36 
37         (
38 
39             a ASC
40 
41         )
42 
43     ) ON [PRIMARY]
44 
45     GO
46 
47     --2.创建测试数据
48 
49     Insert into Table1 values('','asds','90')
50 
51     Insert into Table1 values('','asds','100')
52 
53     Insert into Table1 values('','asds','80')
54 
55     Insert into Table1 values('','asds',null)
56 
57     GO
58 
59     select * from Table2
60 
61 
62 
63     --3.INSERT INTO SELECT语句复制表数据
64 
65     Insert into Table2(a, c, d) select a,c,5 from Table1
66 
67     GO
68 
69 
70 
71     --4.显示更新后的结果
72 
73     select * from Table2
74 
75     GO
76 
77     --5.删除测试表
78 
79     drop TABLE Table1
80 
81     drop TABLE Table2
View Code

2.  2.SELECT INTO FROM语句

      语句形式为:SELECT vale1, value2 into Table2 from Table1

      要求目标表Table2不存在,因为在插入时会自动创建表Table2,并将Table1中指定字段数据复制到Table2中。示例如下:

--1.创建测试表

    create TABLE Table1

    (

        a varchar(10),

        b varchar(10),

        c varchar(10),

        CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED

        (

            a ASC

        )

    ) ON [PRIMARY]

    GO



    --2.创建测试数据

    Insert into Table1 values('','asds','90')

    Insert into Table1 values('','asds','100')

    Insert into Table1 values('','asds','80')

    Insert into Table1 values('','asds',null)

    GO



    --3.SELECT INTO FROM语句创建表Table2并复制数据

    select a,c INTO Table2 from Table1

    GO



    --4.显示更新后的结果

    select * from Table2

    GO

    --5.删除测试表

    drop TABLE Table1

    drop TABLE Table2
View Code

    

生活不是用眼泪博得同情 而是用汗水赢得掌声
原文地址:https://www.cnblogs.com/tutuyforever/p/3454060.html