日期:2014-05-18  浏览次数:20613 次

请教触发器或解决办法
我想实现如下功能:在同一个表中有三列a、b、c,输入一条记录:在输入a列、b列的数值后(未保存此记录时),自动填入C列的数值--等于a列乘以b列,触发器可以实现吗?

------解决方案--------------------
For example:

create table test(a int,b int,c as a*b)
go

insert into test(a,b) values(5,6)
select * from test
go

/*
a b c
----------- ----------- -----------
5 6 30
*/

drop table test
go
------解决方案--------------------
在该记录保存之前计算,不属于数据库吧.

那应该在软件的前端编程时计算, 先判断a , b 是否为数值,
------解决方案--------------------
create trigger tri_insert on t
after update,insert
as
update t
set c=t1.a*t1.b from inserted t1
where t.id=t1.id
------解决方案--------------------
create table t
(
id int identity(1,1),
a int,
b int,
c int
)

create trigger aa on t
after insert ,update
as
update t
set c=t1.a*t1.b
from inserted t1
where t.id=t1.id

insert into t
select 12,10 ,null union all
select 5,6,null

select * from t

id a b c
----------- ----------- ----------- -----------
1 12 10 120
2 5 6 30

(2 row(s) affected)