So, I feel the need to be recorded, so that after the encounter this problem again, and get answers from the idea.
Benpian is trigger the topic, there are a lot of problems trigger.
1, sql unique constraint how to build?
http://bbs.csdn.net/topics/390697861
such as a table the Table1,
three fields A B ID
ID primary key,
when the B value for a particular field value, A field value is to be the only constraint,
if B other field values, a unique without constraint. .
That of constraints not I want, and
I want field is is a (k is a specific value of B)
ID A B
. 1 A B
2 A B
. 3 B K
. 4 C K
if combined on the basis of
A B
B K
, or ck is It can not be allowed.
I would like to direct constraint in the database to see if there is no way, if not, then we must determine the code constraints.
My method:
-
--drop table tb
-
--go
-
-
create
table tb(
ID
int, A
varchar(
10), B
varchar(
10))
-
-
insert
into tb
-
select
1 ,
'a',
'b'
union all
-
select
2 ,
'a',
'b'
union all
-
select
3 ,
'b',
'k'
union all
-
select
4 ,
'c',
'k'
-
go
-
-
-
create
trigger dbo.trigger_tb_insert
-
on dbo.tb
-
for
insert
-
as
-
-
if (
select
count(*)
from inserted i
-
inner
join tb
-
on tb.A = i.A
and tb.B = i.B
-
where i.B =
'k') >
1
-
rollback
-
go
-
-
-
--会报错
-
insert
into tb
-
values(
5,
'b',
'k')
-
/*
-
消息 3609,级别 16,状态 1,第 1 行
-
事务在触发器中结束。批处理已中止。
-
*/
-
-
-
--不会报错
-
insert
into tb
-
values(
5,
'a',
'b')
-
/*
-
(1 行受影响)
-
*/
2, how to achieve a field in a table to calculate the value of a field in another table?
有一张表AA 有字段 a b c
另一张表BB 字段 aa bb cc
如何实现AA表的字段b(为整数型)中的数据 是BB表中的cc字段(为整数型)所有数据记录的总和(sum)!
要求做到BB表数据记录增加的同时AA表中字段b的记录值自动同步更新。
我的建议:
对的,触发器能实现你的需求,另外,索引能加快速度。
因为这种同步的需求,首先,不是跨越服务器的,一般跨越服务器的,可以考虑用数据库同步(异步)、镜像(同步)、日志传送(异步)等技术。
而你现在是在同一台服务器上,要同步2个表的数据,所以用触发器是最合适的,而且触发器本身的特性是,在同一个事务中,只要你的数据插入成功,那么另一个表的数据,也就是同步成功了,同样的,如果插入失败,报错,那么另一个表的数据也不会同步成功。
再有,就是效率的问题,如果每次都sum求和,而你的表里是上亿的数据,这个sum肯定是非常耗时的,所以这里采用的是,你插入1条数据,那么只要把这个插入的数据,通过update 表 set c = c + 插入的值
那么自然就加快了速度,而且不会出现并发的问题。
如果还想进一步加快速度,那么可以考虑,给A表建立索引,因为a表肯定记录也不会少,而且肯定是通过where条件来定义某一条记录,然后update ,这个时候通过索引,就能更快的找到这条记录,然后update。
4、如何实现一张表的某个字段为另一张表的某字段的计算值?
有一张表AA 有字段 a b c
另一张表BB 字段 aa bb cc
如何实现AA表的字段b(为整数型)中的数据 是BB表中的cc字段(为整数型)所有数据记录的总和(sum)!
要求做到BB表数据记录增加的同时AA表中字段b的记录值自动同步更新。
我的建议:
对的,触发器能实现你的需求,另外,索引能加快速度。
因为这种同步的需求,首先,不是跨越服务器的,一般跨越服务器的,可以考虑用数据库同步(异步)、镜像(同步)、日志传送(异步)等技术。
而你现在是在同一台服务器上,要同步2个表的数据,所以用触发器是最合适的,而且触发器本身的特性是,在同一个事务中,只要你的数据插入成功,那么另一个表的数据,也就是同步成功了,同样的,如果插入失败,报错,那么另一个表的数据也不会同步成功。
再有,就是效率的问题,如果每次都sum求和,而你的表里是上亿的数据,这个sum肯定是非常耗时的,所以这里采用的是,你插入1条数据,那么只要把这个插入的数据,通过update 表 set c = c + 插入的值
那么自然就加快了速度,而且不会出现并发的问题。
如果还想进一步加快速度,那么可以考虑,给A表建立索引,因为a表肯定记录也不会少,而且肯定是通过where条件来定义某一条记录,然后update ,这个时候通过索引,就能更快的找到这条记录,然后update。