Sqlserver触发器

一、插入触发器

if (object_id('tgr_hrmresource_insert', 'tr') is not null)
    drop trigger tgr_hrmresource_insert
go
create trigger tgr_hrmresource_insert
on hrmresource
after insert --插入触发
as
begin
    -- 获取当前日期的年份和月份
    declare @year int, @month int;
    select @year = datepart(year, getdate());
    select @month = datepart(month, getdate());
    
    -- 检查是否已经存在当月的记录
    if not exists (select 1 from hrmresource where datepart(year, insert_date) = @year and datepart(month, insert_date) = @month)
    begin
        --定义变量
        declare @id int, @name varchar(20), @temp int;
        --在inserted表中查询已经插入记录信息
        select @id = id, @name = name from inserted;
        set @name = @name + convert(varchar, @id);
        set @temp = @id / 2;    
        insert into student values(@name, 18 + @id, @temp, @id);
        print '添加学生成功!';
    end
end
go