IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_flowwork_delete]') AND type = 'TR')
DROP TRIGGER [dbo].[mps_flowwork_delete]
GO

   

CREATE trigger [dbo].[mps_flowwork_delete] on [dbo].[mps_flowwork] for delete as
begin
    declare
       @numrows  int,
       @errno    int,
       @errmsg   varchar(255)

    select  @numrows = @@rowcount
    if @numrows = 0
       return
    
    declare status1 cursor LOCAL FORWARD_ONLY READ_ONLY for
  select wrk_id , wrk_bizid,biz_cmpid from deleted ,  mps_biztype 
  where wrk_bizid=biz_id 
  open status1
  declare @wrkid int
  declare @bizid int 
  declare @cmpid int
  declare @tbname varchar(50)
declare @dbname varchar(50)
declare @fkey   varchar(50) 
declare @sql nvarchar(1000) 
  FETCH NEXT FROM status1 INTO @wrkid,@bizid,@cmpid
  WHILE (@@FETCH_STATUS = 0)
  BEGIN
  exec sys_sql_getTableNamePk @cmpid,'biz',@bizid,0,@tbname output,@fkey output ,@dbname output 
   if (dbo.checkprocedure(@tbname+'_'+convert(varchar(10),@wrkid)+'_wrkapply_after')=0)
   begin
   set @sql='drop procedure '+@tbname+'_'+convert(varchar(10),@wrkid)+'_wrkapply_after' 
exec(@sql)
end 
if (dbo.checkprocedure(@tbname+'_'+convert(varchar(10),

@wrkid)+'_wrkapply_before')=0)
   begin
   set @sql='drop procedure '+@tbname+'_'+convert(varchar(10),@wrkid)+'_wrkapply_before' 
exec(@sql)
end 
if (dbo.checkprocedure(@tbname+'_'+convert(varchar(10),@wrkid)+'_wrknew_after')=0)
   begin
   set @sql='drop procedure '+@tbname+'_'+convert(varchar(10),@wrkid)+'_wrknew_after' 
exec(@sql)
end 
if (dbo.checkprocedure(@tbname+'_'+convert(varchar(10),@wrkid)+'_wrknew_before')=0)
   begin
   set @sql='drop procedure '+@tbname+'_'+convert(varchar(10),@wrkid)+'_wrknew_before' 
exec(@sql)
end 
if (dbo.checkprocedure(@tbname+'_'+convert(varchar(10),@wrkid)+'_wrknew_start')=0)
   begin
   set @sql='drop procedure '+@tbname+'_'+convert(varchar(10),@wrkid)+'_wrknew_start' 
exec(@sql)
end 
if (dbo.checkprocedure(@tbname+'_endmessage_'+convert(varchar(10),@wrkid))=0)
   begin
   set @sql='drop procedure '+@tbname+'_endmessage_'+convert(varchar(10),@wrkid) 
exec(@sql)
end
if (dbo.checkprocedure(@tbname+'_startmessage_'+convert(varchar(10),

@wrkid))=0)
   begin
   set @sql='drop procedure '+@tbname+'_startmessage_'+convert(varchar(10),@wrkid) 
exec(@sql)
end
   FETCH NEXT FROM status1 INTO @wrkid,@bizid,@cmpid
  END
  CLOSE status1
DEALLOCATE status1 


      update mps_tableupdated set tu_updated=0 where tu_table='mps_flowwork'    and tu_cmpid=@cmpid  
  update mps_biztype set biz_changed = 0  from inserted where wrk_bizid=biz_id and biz_changed=1 
  
 

    return

/*  Errors handling  */
error:
    -- raiserror @errno @errmsg
    rollback  transaction
end