declare @objectID int;
select @objectID = object_id from sys.triggers where parent_id = object_id(N'dbo.ConnectionWiki') and name= N'tr_ConnectionWiki';

if object_id(N'dbo.ConnectionWiki') is not null
begin
    declare @createOrAlter nvarchar(6);
    set @createOrAlter = case when @objectID IS NULL then N'create' else N'alter' end;
    exec (@createOrAlter + N' trigger dbo.tr_ConnectionWiki
on dbo.ConnectionWiki
for insert, update
as
begin
    set nocount on;
    insert into dbo.ConnectionWikiHistory
    (
        HistoryType
      , ConnectionWikiID
      , ConnectionID
      , Name
      , Data
      , ModifiedDate
      , ModifiedUserName
      , ModifiedLoggedUserName
    )
    select
        case
            when d.ID is null then ''I''
            else ''U''
        end
      , i.ID
	  , i.ConnectionID
      , i.Name
      , i.Data
      , case
            when d.ID is null then isnull(i.CreationDate, getutcdate())
            when i.ModifiedDate = d.ModifiedDate then getutcdate()
            else isnull(i.ModifiedDate, getutcdate())
        end
      , case
            when d.ID is null then i.CreationUsername
            else i.ModifiedUserName
        end
      , case
            when d.ID is null then i.CreationLoggedUserName
            else i.ModifiedLoggedUserName
        end
	from inserted as i
		left join deleted as d on d.ID = i.ID;
end;');
end;