create trigger mytrigger on t1 for insert,update as--创建一个关联table:t1触发器 当insert的时候 触发update操作
begin
if(select max(cnt) from
(select count(i.c1) as cnt from t1,--1
inserted i where t1.c1=i.c1 group by i.c1)--2 这两句的意思看不懂 i是什么意思? 是t1的复制吗
x)>1--这里的x又是什么意思?
rollback tran
end
begin
if(select max(cnt) from
(select count(i.c1) as cnt from t1,--1
inserted i where t1.c1=i.c1 group by i.c1)--2 这两句的意思看不懂 i是什么意思? 是t1的复制吗
x)>1--这里的x又是什么意思?
rollback tran
end
inserted是触发器特有的临时表,记录插入时的数据以及update操作时的新数据
x也是表别名,from ()x,from后面一定要有表,用括号括起来的话没有明确的表名
所以一定要加一个表名确定这个括号所代表的表集合
当插入 一条数据到t1的时候触发该触发器,这条数据首先存储到inserted这张临时表里面
然后判断,如果t1表的c1=i.c1的记录》1 就报错 回滚 不插入该条数据
反之插入
嗯 在理解的时候 又发现 一点问题 呵呵
create trigger mytrigger on t1 for insert,update as-
begin
if(select max(cnt) from
(select count(i.c1) as cnt from t1,inserted i where t1.c1=i.c1 group by i.c1)--这里按理说应该是一张表 但是 这里的select返回的不是一个数字吗【count(i.c1) as cnt】
x)>1 --还有这里 怎么是>1呢? 应该是>=1吧【其实=1应该就可以了吧】,等于1说明有一条数据了,就不应该插入了啊
rollback tran
end
这个应该是与基表同时操作的
这是要查询插入的c1值数量,如果插入后重复的数据超过1条,也就是出现了重复数据
就回滚插入操作,这个逻辑同时适用update操作
谢谢 szm341
O(∩_∩)O~