declare @objectID int;
select @objectID = object_id from sys.triggers where parent_id = object_id(N'dbo.Repository') and name = N'tr_Repository';
declare @createOrAlter nvarchar(6);
set @createOrAlter = case when @objectID is null then N'create' else N'alter' end;
exec (@createOrAlter + N' trigger dbo.tr_Repository
on dbo.Repository
for insert, update
as
begin
    set nocount on;

    insert into dbo.RepositoryHistory (HistoryType, RepositoryID, Name, Description, ModifiedDate, ModifiedUserName, ModifiedLoggedUserName, RepositoryType)
    select
        case
            when d.ID is null then ''I''
            else ''U''
        end
        ,i.ID
        ,i.Name
        ,i.Description
        ,case
            when i.ModifiedDate = d.ModifiedDate then getutcdate()
            else isnull(i.ModifiedDate, getutcdate())
        end
        ,i.ModifiedUserName
        ,i.ModifiedLoggedUserName
        ,i.RepositoryType
    from inserted as i
        left join deleted as d on d.ID = i.ID;
end;');