declare @objectID int;
select @objectID = object_id from sys.triggers where parent_id = object_id(N'dbo.Connections') and name= N'tr_Connections_Delete';
if object_id(N'dbo.Connections') 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_Connections_Delete
on dbo.Connections
for delete
as 
begin
	set nocount on

    insert into dbo.ConnectionHistory (HistoryType, ConnectionID, DATA, SecurityGroup, ConnectionType, ConnectionSubType, GroupName, Name, MetaData, CreationDate, Description, ModifiedDate, ModifiedUsername, ModifiedLoggedUserName, Version, RepositoryID, IsSubConnection, IsTemplate, Groups, ConnectionMasterSubType, UrlLink, Keywords, SortPriority, Status, StatusMessage, Image, Expiration, PermissionCacheID)
    select N''D'', ID, DATA, SecurityGroup, ConnectionType, ConnectionSubType, GroupName, Name, MetaData, CreationDate, Description, dateadd(ms, 3, isnull(ModifiedDate, getutcdate())), ModifiedUsername, ModifiedLoggedUserName, Version, RepositoryID, IsSubConnection, IsTemplate, Groups, ConnectionMasterSubType, UrlLink, Keywords, SortPriority, Status, StatusMessage, Image, Expiration, PermissionCacheID from deleted
end
');
end;