当前位置: 代码迷 >> Sql Server >> 创建一个统计数额的触发器
  详细解决方案

创建一个统计数额的触发器

热度:40   发布时间:2016-04-24 10:22:26.0
创建一个统计数目的触发器
theme(theme , introuduction , article_num)     主题(主题,介绍,所含帖子数量)
article(article_id,theme )      帖子(帖子编号,所属主题)

现在要写一个触发器,在主题那个表中显示该主题所含帖子的数量。
小白求教。。
------解决方案--------------------
select 
   a.主题,
    count(b.帖子编号) as 所含帖子数量
from
    theme as a inner join article as b on a.theme=b.theme
group by
    a.主题

------解决方案--------------------
这个确实不需要触发器来做。
一定要的话可以用下面的


 create trigger tr_article 
 on article
 after insert,delete,update
 as begin
  update a set article_num=isnull(b.[count],0)
  from theme a
  join (select theme,count(article) as [count] from article
  group by theme) b on a.theme=b.theme
  where a.articel_num<>isnull(b.[count],0)
 end

------解决方案--------------------
同意楼上

create trigger tr_add_article  -- 增加
 on article 
 after insert
 as 
begin
declare @num = select article_num
  from theme 
 update theme
set article_num= @num+1
 end

create trigger tr_add_article  -- 删除
 on article 
 after Delete
 as 
begin
declare @num = select article_num
  from theme 
 update theme
set article_num= @num-1
 end
  相关解决方案