with cteCleanUpGroupName as
(
    select
        ID
        ,case
            when ConnectionType = 25 and GroupName = Name then ''
            when ConnectionType = 25 and GroupName like '%\' + Name then substring(GroupName, 0, len(GroupName) - len(Name))
            else GroupName end as GroupName
    from dbo.Connections
)
,cteXmlGroups as
(
    select ID, cast('<Group>' + replace(dbo.fn_XMLEscape(replace(GroupName, ';', '||Group||Group|')), '||Group||Group|', '</Group><Group>') + '</Group>' as xml) Xml
    from cteCleanUpGroupName
)
,cteGroups as
(
    select x.ID, ltrim(rtrim(c.value('.','nvarchar(256)'))) as GroupName
    from cteXmlGroups x
        cross apply Xml.nodes('/Group') T(c)
)
,cteGroupsDistinct as
(
    select distinct * from cteGroups
)
insert into dbo.ConnectionGroup (ConnectionID, GroupName )
select x.ID, x.GroupName
from cteGroupsDistinct x
    left outer join dbo.ConnectionGroup g on g.GroupName = x.GroupName and g.ConnectionID = x.ID
where g.ID is null;