sql server 函数与触发器的使用

sql server中触发器的使用

--从临时表中查找指定的专家记录是否存在
create function F_EXPERT_EXIST_IN_TEMP(
   @ExpertId numeric(9),
   @SqlType numeric(9),
   @Trs_flag numeric(9)

)
returns int
as
begin
    declare @ret int
    select @ret = 0
      select @ret = count(*) from [86_xiehe_time$_temp]
      where EXPERTID = @ExpertId and SQL_TYPE = @SqlType and TRS_FLAG = @Trs_flag
    return @ret
end

 

--工作经历触发器(只有专家才有工作经历)
 --新增
 CREATE TRIGGER [WorkHistory_I_TRIG] ON [XWCMWORKHISTORY] FOR INSERT AS
   BEGIN
  --需要判断在临时表中是否已经存在  
  declare @nIsExist int
  select @nIsExist = DBO.F_EXPERT_EXIST_IN_TEMP(OBJID,1,0) from INSERTED
  if(@nIsExist>0)
   return
  --不存在的话则添加到临时表中
      INSERT INTO [86_xiehe_time$_temp] (EXPERTID,SQL_TYPE,TRS_FLAG)
      SELECT OBJID,1,0 FROM INSERTED
   END

GO
 
 --修改
 CREATE TRIGGER [WorkHistory_U_TRIG] ON [XWCMWORKHISTORY] FOR UPDATE AS
   BEGIN
  --需要判断更新前的操作表中有记录  
  declare @nIsExist int
  select @nIsExist = DBO.F_EXPERT_EXIST_IN_TEMP(OBJID,3,0) from DELETED
  if(@nIsExist=0)
   begin
    --不存在的话则添加到临时表中
        INSERT INTO [86_xiehe_time$_temp] (EXPERTID,SQL_TYPE,TRS_FLAG)
       SELECT OBJID,3,0 FROM DELETED
   end

  --判断是否需要添加到更新后的表
  select @nIsExist = DBO.F_EXPERT_EXIST_IN_TEMP(OBJID,1,0) from INSERTED
  if(@nIsExist=0)
   begin
        INSERT INTO [86_xiehe_time$_temp] (EXPERTID,SQL_TYPE,TRS_FLAG)
        SELECT OBJID,1,0 FROM INSERTED
   end
   END

GO
 
 --删除
 CREATE TRIGGER [WorkHistory_D_TRIG] ON [XWCMWORKHISTORY] FOR DELETE AS
   BEGIN
  --需要判断在临时表中是否已经存在  
  declare @nIsExist int
  select @nIsExist = DBO.F_EXPERT_EXIST_IN_TEMP(OBJID,3,0) from DELETED
  if(@nIsExist>0)
   return

  --不存在的话则添加到临时表中
      INSERT INTO [86_xiehe_time$_temp] (EXPERTID,SQL_TYPE,TRS_FLAG)
      SELECT OBJID,3,0 FROM DELETED
   END

GO

你可能感兴趣的:(sql server 函数与触发器的使用)