• 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

  • 相关阅读:
    Linux文件默认权限和umask笔记
    Linux文件默认权限和umask笔记
    Linux关于文件的权限笔记
    Linux关于文件的权限笔记
    Linux文件和目录权限笔记
    Linux文件和目录权限笔记
    Linux文件目录基础笔记
    Linux文件目录基础笔记
    spark在collect收集数据的时候出现outOfMemoryError:java heap space
    查看hadoop压缩方式
  • 原文地址:https://www.cnblogs.com/sunShineJing/p/4001655.html
Copyright © 2020-2023  润新知