关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

mssql经典触发器:添加时触发包含判断

发布时间:2019-11-05 15:41:44


USE [kmgaj]

GO

/****** Object:  Trigger [dbo].[insert_dt_article]    Script Date: 03/08/2019 15:01:34 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

-- =============================================

-- Author:<Author,大王>

-- Create date: <2019-3-8>

-- Description:<数据中心:www.yn137.com,试验室:lab.yn137.com>

-- =============================================

ALTER TRIGGER [dbo].[insert_dt_article]

   ON  [dbo].[dt_article]

   AFTER INSERT

AS 

   DECLARE @user_name varchar(255);--定义变量 用户名

   declare @group_id  int;         --定义变量 用户组id

   declare @group_title varchar(255);

   declare @user_id   int;         --定义变量 用户id

   declare @iscount   varchar(10); --用户是否存在统计库dt_count里

   SELECT  @user_name=user_name FROM INSERTED; --得到用户名

   if @user_name<>'' 

BEGIN

   select @group_id=group_id,@user_id=id from dt_users where user_name=@user_name; --得到组id和用户id

   select @group_title=title from dt_user_groups where id=@group_id;--得到组标题

   

    if exists(select top 1 * from dt_count where user_name=@user_name)

       begin

         select @iscount='yes';

       end

    else

       begin

         select @iscount='no';

       end   

   

END

BEGIN

   if (@iscount='no')

   begin

--update dt_count set note=@iscount;--测试

insert into dt_count (add_num,group_id,group_title,user_id,user_name) values (1,@group_id,@group_title,@user_id,@user_name);

   end

   else

   begin

update dt_count set add_num=add_num+1,up_time=getdate() where user_name=@user_name;--添加数加1

   end

   

   --update dt_count set note=@iscount;--测试

   

-- SET NOCOUNT ON added to prevent extra result sets from

-- interfering with SELECT statements.

SET NOCOUNT ON;


    -- Insert statements for trigger here


END

2.png



/template/Home/Zkeys/PC/Static