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

if object_id(N'dbo.ConnectionHandbook') 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_ConnectionHandbookCount
on dbo.ConnectionHandbook after insert, delete
as 
begin
    with cteRows as
    (
        select ConnectionID from inserted i union select ConnectionID from deleted d
    )
    ,cteUpdate as 
    (
		select r.ConnectionID, isnull(count(distinct t.ID), 0) as HandbookCount
		from cteRows r
			left outer join dbo.ConnectionHandbook t on t.ConnectionID = r.ConnectionID
		group by r.ConnectionID
    )
    update c
    set HandbookCount = cte.HandbookCount
    from dbo.Connections c
        inner join cteUpdate cte on cte.ConnectionID = c.ID
    where isnull(c.HandbookCount, 0) <> isnull(cte.HandbookCount, 0);
end');
end;