+ -
当前位置:首页 → 问答吧 → 触发器

触发器

时间:2011-12-16

来源:互联网

表 A 有字段 id content  
我想写个触发器,后台往表A 写入数据的时,检查字段content的内容是不是包括 'ABC'
如果不包括,则让其写入表 A 中。包括则删除此条数据
这个触发器该如何实现?

作者: wo_shi_liudong   发布时间: 2011-12-16

SQL code
create trigger tr_name on A
for insert
as
begin
    if exists(select 1 from inserted where content like '%A%')
      delete A from A,inserted t where A.id=t.id and A.content=t.content
end

作者: ssp2009   发布时间: 2011-12-16

SQL code

if object_id('a') is not null
   drop table a
go
create table a
(
 id int,
 content varchar(10)
)
go
if object_id('tr_a_insert') is not null
   drop trigger tr_a_insert
go
create trigger tr_a_insert on a
for insert
as
  if exists(select 1 from inserted where content like '%abc%')
     rollback
go
insert into a select 1,'123'
insert into a select 2,'6abc6'
select * from a
/*
id          content
----------- ----------
1           123

(1 行受影响)

*/


作者: pengxuan   发布时间: 2011-12-16

SQL code

Create trigger a_Ins On a for insert
as
    Delete From a Where Exists(Select 1 From inserted i Where a.id=i.id And i.content like '%ABC%')

--这个最好在程序里面排除掉。在数据库有点效率低啊。



作者: mustudent   发布时间: 2011-12-16

SQL code
[code=SQL]create trigger test on a
for insert
as
begin
declare @content varchar(100)
set @content='xx'
  if exists(select 1 from inserted where content like '%abc%')
     rollback
  else 
  insert into a(content) select @content 
go
[/code]

作者: fredrickhu   发布时间: 2011-12-16

SQL code
create trigger test on a
for insert
as
begin
declare @content varchar(100)
set @content='xx'
  if exists(select 1 from inserted where content like '%abc%')
  delete A from A,inserted i where A.id=i.id and A.content=i.content and i.content=@content 
  else 
  insert into a(content) select @content 
go

作者: fredrickhu   发布时间: 2011-12-16

直接在INSERT前先判断下是否包含 'ABC',不包含才INSERT不是比你这个效率更高些吗?

作者: gogodiy   发布时间: 2011-12-16