zoukankan      html  css  js  c++  java
  • SQL学习之--触发器

    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

  • 相关阅读:
    第九周进度条
    梦断代码阅读笔记01
    NABCD分析
    软件工程个人作业05
    HDU 3949 XOR(线性基)
    luogu 2115 破坏(01分数规划)
    luogu 1360 阵容均衡(前缀和+差分+hash)
    luogu 1967 货车运输(最大生成树+LCA)
    luogu 1344 追查坏牛奶(最小割)
    BZOJ 2007 海拔(平面图最小割转对偶图最短路)
  • 原文地址:https://www.cnblogs.com/sunShineJing/p/4001655.html
Copyright © 2011-2022 走看看