码迷,mamicode.com
首页 > 数据库 > 详细

SQL学习之--触发器

时间:2014-09-30 13:08:59      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   io   ar   数据   sp   div   

USE [learn2]
GO
/****** Object:  Trigger [dbo].[trigger_AdClass]    Script Date: 09/30/2014 09:01:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:        <Author,,sushine>
-- Create date: <Create Date,,2014-9-29>
-- Description:    <Description,,保证子父级 webpageId 关联一致;或者子级单独是可以的>
-- =============================================
create TRIGGER [dbo].[trigger_AdClass] on [dbo].[AdClass]
   AFTER insert,update
AS 
BEGIN try
    declare @err nvarchar(256),@classId int,@parentId int;
    if(exists(select 1 from inserted))--当增加一条数据的时候和当修改parentId的时候
    begin
        select @classId=classId from inserted;
        select @parentId=parentId from inserted;
        if(@parentId is not null)
        begin
            update AdClass set WebPageId=(select WebPageId from AdClass where ClassId=@parentId) where AdClass.ClassId=@classId;
        end
    end
    if(update(webpageId))--当修改webpageId的时候
    begin
        select @classId=classId from inserted;
        update AdClass set WebPageId=i.WebPageId from inserted i where adclass.ClassId in(select ClassId from dbo.AdClassTree(@classId,null) where Depth>1);
    end
    --else if(update(parentId))
    --begin
    --    select @parentId= parentId from inserted;
    --    select @classId=classId from inserted;
    --    update AdClass set WebPageId=(select WebPageId from AdClass where ClassId=@parentId) where adclass.ClassId=@classId;
    --end
end try    
begin catch
    rollback;
    set @err=ERROR_MESSAGE();
    Raiserror(@err,16,0);
end catch


触发器   inserted  和 deleted  两种。

 

当insert 和update的时候用inserted

 

SQL学习之--触发器

标签:des   style   blog   color   io   ar   数据   sp   div   

原文地址:http://www.cnblogs.com/sunShineJing/p/4001655.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!