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

    insert into dbo.ConnectionState (ID, ConnectionID, RepositoryID, UserID, State, MachineName, CreationDate, CreationUsername, CreationLoggedUserName)
    select i.ID, i.ConnectionID, isnull(i.RepositoryID, ''00000000-0000-0000-0000-000000000000''), i.UserInfoID, 2 /* Running */, i.MachineName, i.StartDateTime, i.Username, i.LoggedUserName
    from inserted i
    where i.MessageType in (4, 8)
      and i.SupportClose = 1
      and i.EndDateTime is null;
end;');