Copy Code Trigger Definition

        
    CREATE trigger TR_CONSTITUENCY_TASYNC_I on dbo.CONSTITUENCY after insert not for replication
    as begin
      if dbo.UFN_B2T_CONTEXTISSYNC() = 0
      begin
        insert into dbo.TA_CONSTITUENCY (ID, SYNCID, ACTIONCODE)
        select INSERTED.ID, newid(), 1
        from INSERTED
        -- only insert constituencies using codes mapped from classifications

        inner join dbo.B2TROWS jclassification_code on jclassification_code.TATABLE = 'T2B_CLASSIFICATION_VALUE' and jclassification_code.BBECTABLE = 'CONSTITUENCYCODE' and jclassification_code.BBECID = INSERTED.CONSTITUENCYCODEID

        -- note that the above insert could fail if row is deleted and then reinserted w/ same ID before sync is run

        -- since we would not know anything about whether the row is really the same or not, we need to throw an exception

        -- to resolve, run the sync, then retry the insert

        
        update dbo.TA_CONSTITUENT
        set ACTIONCODE = case when ACTIONCODE=1 then 1 else 2 end
        where ID in(select INSERTED.CONSTITUENTID
                    from INSERTED
                    inner join dbo.B2TROWS r on r.TATABLE = 'ACCOUNT_TYPE' and r.BBECTABLE = 'CONSTITUENCYCODE' and r.BBECID = INSERTED.CONSTITUENCYCODEID);
                    
        update dbo.TA_ACCOUNTS
        set ACTIONCODE = case when ACTIONCODE=1 then 1 else 2 end
        where ID in(select INSERTED.CONSTITUENTID
                    from INSERTED
                    inner join dbo.B2TROWS r on r.TATABLE = 'ACCOUNT_TYPE' and r.BBECTABLE = 'CONSTITUENCYCODE' and r.BBECID = INSERTED.CONSTITUENCYCODEID);
      end
    end