(1)最常用的INSERT语句的形式如下:
INSERT INTO <table> (<column list>) VALUES(<value>,<value>,...n)
--从一个表中查出数据导入到另一个表中
INSERT INTO <table> (<column list>)-- SELECT <column list> FROM <table>
(2)SELECT INTO 语句
SELECT <COLUMN LIST> INTO <#TABLE>--新表本身不存在 FROM <TABLE>
(3)更新数据
UPDATE <table> set column='',...
(4)删除数据
DELETE FROM <TABLE > --一般有限制条件
truncate table <table> -- 将表删除;能够清除自增长列
(5)MERGE 语句(***************转载)
使用方法:
Merge Into 目标表 as T
Using 源表 as S
ON 匹配条件
when matched and [其它条件] then
对源表与目标表匹配的项执行的操作
when not matched [其它条件] then
对源表中存在的,而目标表中不存在的匹配项执行操作
when not matched by source and [其它条件] then
对目标表中存在的,而源表中不存在的匹配项执行操作;
注意事项 1.最后的分号必须有
2.源表可以是一个具体的表,也可以是一个子查询语句
CREATE TABLE Old(ID INT,Des nvarchar(20)) --创建目标表 CREATE TABLE New(ID INT,Des nvarchar(20)) Insert into Old Values(1,'1') Insert into Old Values(2,'2') --目标表中不存在的将被插入 Insert into Old Values(3,'3') Insert into New Values(1,'匹配的将被修改') Insert into New Values(5,'源表中不存在的将被删除') Merge into New AS T Using Old as S ON T.ID=S.ID WHEN MATCHED THEN UPDATE SET T.Des=S.Des WHEN NOT MATCHED THEN INSERT VALUES(S.ID,S.Des) WHEN NOT MATCHED BY Source THEN DELETE
Mergo还一个强大功能,用Output可以对刚才做的改动输出:
CREATE TABLE Old(ID INT,Des nvarchar(20)) --创建目标表 CREATE TABLE New(ID INT,Des nvarchar(20)) Insert into Old Values(1,'1') Insert into Old Values(2,'2') --目标表中不存在的将被插入 Insert into Old Values(3,'3') Insert into New Values(1,'匹配的将被修改') Insert into New Values(5,'源表中不存在的将被删除') Merge into New AS T Using Old as S ON T.ID=S.ID WHEN MATCHED THEN UPDATE SET T.Des=S.Des WHEN NOT MATCHED THEN INSERT VALUES(S.ID,S.Des) WHEN NOT MATCHED BY Source THEN DELETE; output $action as [Action],Inserted.ID AS 插入修改的ID,Inserted.Des as 插入修改的Des, DELETEd.ID AS 修改删除的ID,DELETED.Des as 修改删除的Des;
(6)事务处理
begin tran declare @error int=0 --sql set @error=@error+@@error --sql set @error=@error+@@error if(@error=0) begin commit tran end else begin rollback tran
end
原文:http://www.cnblogs.com/huami/p/3554930.html