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

SQL简单触发器

时间: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%')
      rollback
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 test on a
for insert
as
  if exists(select 1 from inserted where content like '%abc%')
     rollback
go

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

insert into a select 1,'123'
insert into a select 2,'6abc6'
insert into a select 3,'1231212'
这样的话,最后一条也插入不进去的

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

一起执行肯定是不行的,相当一个批处理,出错的地方就停止了

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

create trigger tr_name on A
for insert
as
begin
  if exists(select 1 from inserted where content like '%ABC%')
  rollback
end

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

能改下这个触发器,让不包含ABC的插入进去,不包含的排除在外面吗。有这样的办法吗?

引用 4 楼 wo_shi_liudong 的回复:
insert into a select 1,'123'
insert into a select 2,'6abc6'
insert into a select 3,'1231212'
这样的话,最后一条也插入不进去的

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

看有办法让不包含 ABC 内容的 插入成功,不包括的排除在外面吗?

引用 4 楼 wo_shi_liudong 的回复:
insert into a select 1,'123'
insert into a select 2,'6abc6'
insert into a select 3,'1231212'
这样的话,最后一条也插入不进去的

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

引用 4 楼 wo_shi_liudong 的回复:
insert into a select 1,'123'
insert into a select 2,'6abc6'
insert into a select 3,'1231212'
这样的话,最后一条也插入不进去的
看有办法让不包含 ABC 内容的 插入成功,不包括的排除在外面吗?

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

SQL code
create trigger test on a
for insert
as
  if exists(select 1 from inserted where content like '%abc%')
     rollback
  else 
  insert into a(content) select @content 
go

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

看你前面的帖子,后台难道不是一条一条输入的吗?

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