sql server 函數與觸發器的使用

來源:互聯網
上載者:User

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.