1

我正在尝试编写触发器,它将在表中插入缺失值。我正在使用 SQL Server Express 我有表

create table test 
(suma int ,
summ_year int,
summ_month int 
);

然后我插入一个测试值

INSERT  into test (suma)values (4951)

比我创建的触发器应该根据summ表中的值计算值

create trigger updatetest
on test
AFTER update
as update test
set summ_year = round(suma*1.85,0 ),summ_month = round(summ_year/12,0)

它在哪里1.85是固定值,12是几个月

比我更新 suma

update test  set suma = 4950

并选择检查它是如何工作的

select * from test

从选择返回看起来像这样4950 9158 NULL 但是我的触发器的第二部分应该计算summ_month = round(summ_year/12,0)返回给我 NULL 值。

当我运行这个选择时

select summ_month = round(summ_year/12,0) from test

这是工作。任何想法如何解决它?

4

1 回答 1

1

Why not just use computed columns:

create table test 
(suma int ,
summ_year as round(suma*1.85,0 ),
summ_month as round(round(suma*1.85,0 )/12,0) 
);

No trigger, no muss, no fuss.

As to why your UPDATE isn't working? The expressions in the SET statement are meant to be computed as if they're evaluated in parallel. They're certainly not evaluated from left to right. So, at the point at which you're computing summ_month = round(summ_year/12,0), summ_year hasn't been updated yet and is still NULL.

A nice consequence of this behaviour is that to swap the value of two columns, you need only write:

UPDATE tab SET a = b, b = a

And it does the right thing.

If you do want (for some odd reason) to continue to perform these calculations in a trigger, you'll have to do as I did for the computed columns up at the top - repeat the expression for computing the year value in calculating the month value:

update test
set summ_year = round(suma*1.85,0 ),summ_month = round(round(suma*1.85,0 )/12,0)
于 2013-03-01T07:06:46.363 回答