在SQL Server 2005中使用OUTPUT完成数据操作时的备份

来源:互联网 发布:ubuntu复制目录命令 编辑:程序博客网 时间:2024/04/27 18:20
use tempdb;
go
create table itest ( i int identity not null primary key, j int not null unique );
go
create trigger insert_itest on itest after insert
as
begin
    insert into #new ( i, j )
    select i, j
      from inserted;
end
go
create table #new ( i int not null, j int not null );
insert into itest ( j )
select o.id from sysobjects as o;

-- Newly inserted rows and identity values:
select * from #new;

-- #new can be used now to insert into a related table:
drop table #new, itest;
go

 
在SQL Server 2005中可以将上面的插入操作进行重新组合:
--即:插入数据和保存历史记录同时完成
insert into itest (j)
output inserted.i, inserted.j into #new




使用OUTPUT可以简化代码和同时完成数据的更新删除和保存历史的操作,
如下例Update、Delete:


 
create table t ( i int not null );
create table t_audit ( old_i int not null, new_i int null );

insert into t (i) values( 1 );
insert into t (i) values( 2 );
 
update t
   set i  = i + 1
output deleted.i, inserted.i into t_audit
 where i = 1;
 
delete from t
output deleted.i, NULL into t_audit
 where i = 2;
 
select * from t;
select * from t_audit;
 
drop table t, t_audit;
go

附:OUTPUT语法
  1. 1、OUTPUT_CLAUSE定义(语法参Transact-SQL 语法约定):

  2. <OUTPUT_CLAUSE> ::=
  3. {
  4.     [ OUTPUT <dml_select_list> INTO { @table_variable | output_table } [ ( column_list ) ] ]
  5.     [ OUTPUT <dml_select_list> ]
  6. }
  7. <dml_select_list> ::=
  8. { <column_name> | scalar_expression } [ [AS] column_alias_identifier ]
  9.     [ ,...n ]

  10. <column_name> ::=
  11. { DELETED | INSERTED | from_table_name } . { * | column_name }

  12. 2、OUTPUT_CLAUSE说明:
  13.     返回受 INSERT、UPDATE 或 DELETE 语句影响的每行的信息,或者返回基于上述每行的表达式。这些结果可以返回到处理应用程序,以供在确认消息、存档以及其他类似的应用程序要求中使用。此外,也可以将结果插入表或表变量。

  14. 3、典型应用:
  15.     1、根据当前表的数据有条件的生成历史或新的初始化数据;
  16.     2、把INSERT、UPDATE 或 DELETE 语句影响的每行的信息暂存处理或反馈给应用程序完成业务或逻辑的完整性;
  17.     3、OUTPUT 子句对于在 INSERT 或 UPDATE 操作之后检索标识列或计算列的值可能非常有用;

原创粉丝点击