MSSQL2005 INSERT,UPDATE,DELETE 之OUTPUT子句使用实例
只要相爱,综漫之睡神养成计划,罗照辉
-->title:generating test data
-->author:wufeng4552
-->date :2009-10-07 15:16:26
if object_id('ta')is not null drop table ta
go
create table ta(id int identity,[name] varchar(10))
insert ta([name]) select 'a' union all
select 'b' union all
select 'c' union all
select 'd' union all
select 'e' union all
select 'f' union all
select 'g'
if object_id('tb')is not null drop table tb
go
create table tb(id int identity,[name] varchar(10))
insert tb([name]) select 'a' union all
select 'b' union all
select 'c'
--insert 陳述式來使用 output into
insert tb output
inserted.id,
inserted.[name]
select [name]
from ta where not exists(select 1 from tb where [name]=ta.[name])
/*
id name
----------- ----------
4 d
5 e
6 f
7 g
*/
--刪除剛才插入的紀錄
delete tb where [name]>'c'
--储存此结果集保存到一个表值变量中
declare @t table(id int,[name] varchar(10))
insert tb output
inserted.id,
inserted.[name]into @t
select [name] from ta where not exists(select 1 from tb where [name]=ta.[name])
select * from @t
/*
id name
----------- ----------
8 d
9 e
10 f
11 g
(4 個資料列受到影響)
*/
--delete 陳述式使用 output
delete tb output deleted.* where id=9
/*
id name
----------- ----------
9 e
(1 個資料列受到影響)
*/
-- update 陳述式使用 output into
update tb set [name]='test' output inserted.* where id=10
/*
id name
----------- ----------
10 test
(1 個資料列受到影響)
*/
/*
output 子句对于在 insert操作之后检索标识列或计算列的值可能非常有用。
另外output子句也可以在update和delete语句中使用,从插入表或删除表中得到数值,并返回这些数值。
以下语句中不支持 output 子句:
l 引用本地分区视图、分布式分区视图或远程表的 dml 语句。
l 包含 execute 语句的 insert 语句。
l 不能将 output into 子句插入视图或行集函数。
简洁的output子句,使得向sql server导入数据的操作得到了极大的简化。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!!
点击进行留言回复
相关文章:
-
-
sql某个日期是当年的第几周
/* *周一作为一周的开始 *当年的1月1号所在的周算作第一周 */ CREATE function GetWeekIndexFirstDate ( @...
[阅读全文]
-
-
数据库SQL---范式
1、数据冗余导致的问题:冗余存储、更新异常、插入异常、删除异常。 2、函数依赖:一种完整性约束。 在关系模式r(R)中,α属于R,β属于R。 1)α函数...
[阅读全文]
-
-
数据库SQL---查询
1、查询所有列 select *from emp;--*表示所有的,from emp表示从emp表中查询。 2、查询指定列 select empno,e...
[阅读全文]
-
-
-
-
-
网友评论