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

这样的需求 触发器怎么写 sql
C# code
我有一张表树形表(TreeGrid),字段是 id parent ishaveleaf(是否含有叶子节点)
当这张表发生变化的时候,我就检查是否含有叶子节点,如果含有就更新ishaveleaf的值为1否则为0

请问这样的触发器怎么写? 

我用的是sqlserver2005


------解决方案--------------------
好久没写触发器了,不保证语法全部正确
SQL code
CREATE TRIGGER TIG1 ON TREEGRID
AS
BEGIN
UPDATE T1
SET T1.ISHAVLEAF=CASE WHEN EXISTS(
SELECT 1 FROM TREEGRID T2 WHERE T2.PARENTID=T1.ID
) THEN 1 ELSE 0 END
FROM TREEGRID T1
INNER JOIN INSERTED T2 ON T1.ID=T2.ID OR T1.ID=T2.PARENTID
END

------解决方案--------------------
看错了 可以写
SQL code
create table csdn(id int identity, parent int ,ishaveleaf int)
insert csdn(parent,ishaveleaf)  
select 1,0 
union all select 4,0
select * from csdn

alter trigger ins_csdn
 on csdn
 for insert 
as 
begin
   if exists(select * from csdn a,inserted b where a.id=b.id and a.ishaveleaf=1 )
   return
   else
   update csdn set ishaveleaf=1 from  csdn a,inserted b where a.id=b.parent
end