一。SELECT INTO FROM 和 INSERT INTO SELECT 两种批量新规(表复制)语句
INSERT是T-SQL中常用语句,INSERT INTO table(field1,field2,...) VALUES (value1,value2,...)这种形式在应用程序开发中必不可少。但我们在开发、测试过程中,经常会遇到需要表复制的情况,如将一个table1的数据的部分字段复制到table2中,或者将整个table1复制到table2中,这时候我们就要使用SELECT INTO 和 INSERT INTO SELECT 表复制语句了。
1.INSERT INTO SELECT语句
语句形式为:Insert into Table2(field1,field2,...) select value1,value2,... from Table1
要求目标表Table2必须存在,由于目标表Table2已经存在,所以我们除了插入源表Table1的字段外,还可以插入常量。示例如下:
View Code
1 --1.创建测试表 2 create TABLE Table1 3 ( 4 a varchar(10), 5 b varchar(10), 6 c varchar(10), 7 CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED 8 ( 9 a ASC 10 ) 11 ) ON [PRIMARY] 12 13 create TABLE Table2 14 ( 15 a varchar(10), 16 c varchar(10), 17 d int, 18 CONSTRAINT [PK_Table2] PRIMARY KEY CLUSTERED 19 ( 20 a ASC 21 ) 22 ) ON [PRIMARY] 23 GO 24 --2.创建测试数据 25 Insert into Table1 values('赵','asds','90') 26 Insert into Table1 values('钱','asds','100') 27 Insert into Table1 values('孙','asds','80') 28 Insert into Table1 values('李','asds',null) 29 GO 30 select * from Table2 31 32 --3.INSERT INTO SELECT语句复制表数据 33 Insert into Table2(a, c, d) select a,c,5 from Table1 34 GO 35 36 --4.显示更新后的结果 37 select * from Table2 38 GO 39 --5.删除测试表 40 drop TABLE Table1 41 drop TABLE Table2
2.SELECT INTO FROM语句
语句形式为:SELECT vale1, value2 into Table2 from Table1
要求目标表Table2不存在,因为在插入时会自动创建表Table2,并将Table1中指定字段数据复制到Table2中。示例如下:
View Code
1 --1.创建测试表 2 create TABLE Table1 3 ( 4 a varchar(10), 5 b varchar(10), 6 c varchar(10), 7 CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED 8 ( 9 a ASC 10 ) 11 ) ON [PRIMARY] 12 GO 13 14 --2.创建测试数据 15 Insert into Table1 values('赵','asds','90') 16 Insert into Table1 values('钱','asds','100') 17 Insert into Table1 values('孙','asds','80') 18 Insert into Table1 values('李','asds',null) 19 GO 20 21 --3.SELECT INTO FROM语句创建表Table2并复制数据 22 select a,c INTO Table2 from Table1 23 GO 24 25 --4.显示更新后的结果 26 select * from Table2 27 GO 28 --5.删除测试表 29 drop TABLE Table1 30 drop TABLE Table2
二。批量更新
语句形式为:UPDATE Table2 SET Field1 = Field21, Field2 = Field22 from Table1
实例是项目中用到的,如下:
UPDATE table2 SET filed1 = A.filed1 ,filed2 = A.filed2 ,filed3 = A.filed3 ,filed4 = A.filed4 ,B_DATE = GETDATE() FROM (SELECT LEFT(xxx,4) AS id1 , RTRIM(SUBSTRING(xxx,5,3)) AS id2 , LEFT(LEFT(STRAS,CHARINDEX('' '',xxx)-1),60) AS filed1 , RTRIM(LEFT(STUFF(STRAS,1,CHARINDEX('' '',xxx),''''),60)) AS filed2 , RTRIM(LEFT(xxx,30)) AS filed3 , RTRIM(LEFT(xxx,30)) AS filed4 FROM table1) A INNER JOIN table2 as B ON A.id1 = B.id1 AND A.id2 = B.id2