加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

SQLServer 触发器 数据库进行数据备份

发布时间:2020-12-12 07:52:37 所属栏目:MsSql教程 来源:网络整理
导读:感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧! 代码如下: create table test3(id int primary key not null identity(1,1),uname varchar(20),uage int); create table test3_bak(id int primary key not null identity(1,bid int, u

感兴趣的小伙伴,下面一起跟随编程之家 52php.cn的小编两巴掌来看看吧!

代码如下:

 
  create table test3(id int primary key not null 
  identity(1,1),uname varchar(20),uage int); 
  create table test3_bak(id int primary key not 
  null identity(1,bid int,  uage int,active char(1)); 

  第二步,编写备份用的触发器,只有更新或者是插入的时候才触发

代码如下:

 
  alter trigger test3_bak_insert_update 
  on test3 
  for insert,update 
  as 
  declare @id int 
  declare @uname varchar(20) 
  declare @uage int 
  begin 
  select @id=id,@uname=uname,@uage=uage from inserted 
  if @id<>0 
  begin 
  update test3_bak set active='0' where bid=@id 
  insert into test3_bak(bid,uname,uage,active) 
  values(@id,@uname,@uage,'1') 
  end 
  end 

  第三步,测试数据:

代码如下:

 
  insert into test3(uname,uage) values('FLB',20) 
  insert into test3(uname,uage) values('FLB1',21) 
  insert into test3(uname,uage) values('FLB2',22) 
  update test3 set uage=100 where id=27 
  delete from test3 where id=20 

  最后,你可自己采用下面方法查询跟踪两个表的数据变化:

代码如下:

 
  select * from test3 
  select * from test3_bak 

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读