SQL简单语句查询中经常需要用到(1.将一张表中的内容复制到另一张表;2.或者将查询的内容插入到指定表;3.或者将一个表中部分内容更新成另一张表中的内容),这时了解一下insert into select 跟 select into 以及 update另一张表内容的用法和区别是及有用的
一、insert into select 语句:
语法:
insert into table1 (列1,列2,...) select value1,value2,... from table2 where ... --或者: insert into tabel1 select * from tabel2 where ... --将table2中符合条件的值插入(复制)到tabel1中去.
注意事项:
(1)要求目标表tabel1必须存在,并且字段(列1,列2...)也必须存在。
(2)注意目标表table1的主键约束,如果table1有主键而且不为空,列1,列2...中必须包括主键
(3)注意语法,不要加values,不要和插入一条数据的SQL语句混淆了,不要写成:
insert into table1(列1,列2,...) values(select value1,value2,... from table2 where ...)
二、select into 语句:
语法:
select value1, value2,... into table1 from table2 --将table2中符合条件的值插入(复制)到tabel1中去.
注意事项:
要求目标表table1不存在,因为再插入时会自动创建表table1,并将table2中制定的字段数据复制到table1中去。
三、update(将一张表中的数据更新成另一张表中对应的数据):
语法:
update table1 set table1.列1=table2.列1,table1.列2=table2.列2 from table2 where table1.id=table2.id --或者 update table1 set table1.列1=t2.列1,table1.列2=t2.列2 from table2 t2 where table1.id=t2.id
例如:
update [PS].[T_Bas_WaterOutput] set [PS].[T_Bas_WaterOutput].Longitude = t2.Longitude,[PS].[T_Bas_WaterOutput].Latitude=t2.Latitude from [PS].[T_Bas_Equipment] t2 where [PS].[T_Bas_WaterOutput] .OutportCode = t2.OutportCode --将[PS].[T_Bas_WaterOutput]表中的Longitude,Latitude更新成[PS].[T_Bas_Equipment]表中Longitude,Latitude对应的值。
出处:http://blog.sina.com.cn/s/blog_7c7ec19b0100u6vb.html