Insert is a common statement in T-sql, Insert INTO table(field1,field2,...) values(value1,value2,...) in this form Essential in application development. However, in the process of development and testing, we often encounter situations that require table replication, such as copying part of the data of a table1 to table2, or copying the entire table1 to table2. At this time, we will use SELECT INTO and INSERT INTO SELECT table replication statement too.
1. The form of the INSERT INTO SELECT statement
is:
Insert into Table2(field1,field2,...) select value1,value2,... from Table1
It is required that the target table Table2 must exist . Since the target table Table2 already exists, we can insert constants in addition to the fields of the source table Table1. An example is as follows:
--1. Create a test table create TABLE Table1 ( a varchar(10), b varchar(10), c varchar(10), CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED ( a ASC ) ) ON [PRIMARY] create TABLE Table2 ( a varchar(10), c varchar(10), d int, CONSTRAINT [PK_Table2] PRIMARY KEY CLUSTERED ( a ASC ) ) ON [PRIMARY] GO --2. Create test data 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 select * from Table2 --3.INSERT INTO SELECT statement to copy table data Insert into Table2(a, c, d) select a,c,5 from Table1 GO --4. Display the updated results select * from Table2 GO --5. Delete the test table drop TABLE Table1 drop TABLE Table2
2. The form of the SELECT INTO FROM statement
is:
SELECT vale1, value2 into Table2 from Table1
It is required that the target table Table2 does not exist , because the table Table2 will be automatically created when inserting, and the specified field data in Table1 will be copied to Table2. An example is as follows:
--1. Create a test table create TABLE Table1 ( a varchar(10), b varchar(10), c varchar(10), CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED ( a ASC ) ) ON [PRIMARY] GO --2. Create test data 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 statement to create table Table2 and copy data select a,c INTO Table2 from Table1 GO --4. Display the updated results select * from Table2 GO --5. Delete the test table drop TABLE Table1 drop TABLE Table2
Original address: http://www.cnblogs.com/freshman0216/archive/2008/08/15/1268316.html