判断字段是否为空后赋值给新字段
如上图,希望写一段触发器,在保存时判断前四个字段是否等于0,把不等于0的字段个数赋值给FInteger3,试过isnull和case函数都不行,请做过的给个示例,谢谢。 判断字段是否为空
[解决办法]
-- 建表
create table sh
(FBase2 int, FBase3 int, FBase4 int, FBase5 int, FInteger3 int)
-- 建触发器
create trigger tr_sh on sh
after update,insert
as
begin
update a
set a.FInteger3=case when a.FBase2<>0 then 1 else 0 end
+case when a.FBase3<>0 then 1 else 0 end
+case when a.FBase4<>0 then 1 else 0 end
+case when a.FBase5<>0 then 1 else 0 end
from sh a
inner join inserted b
on a.FBase2=b.FBase2 and a.FBase3=b.FBase3 and a.FBase4=b.FBase4 and a.FBase5=b.FBase5
end
-- 测试
insert into sh(FBase2,FBase3,FBase4,FBase5)
select 25798, 39904, 30775, 0 union all
select 39914, 39904, 17941, 27705 union all
select 39907, 0, 0, 0 union all
select 35025, 30775, 0, 0
-- 结果
select * from sh
/*
FBase2 FBase3 FBase4 FBase5 FInteger3
----------- ----------- ----------- ----------- -----------
25798 39904 30775 0 3
39914 39904 17941 27705 4
39907 0 0 0 1
35025 30775 0 0 2
(4 row(s) affected)
*/