Wednesday, July 31, 2019

Getting the Full Path of a CMS folder from MSDB

Nice, even though I posted this at 12:25am CST on 8/1, blogger still gave me credit for a July post. It has been a busy month as we prepare for a DR exercise next month but I wanted to share this. We build CMS groups for different groups of servers that we need to run scripts against for the DR exercise: Availability Group servers on the production side who are primary, mirrored servers on the DR side, non-participating AGs, etc.

I was writing code to populate all these groups and found that when you query msdb to find the group name it only shows the name of that level and not the full path. I had to write a recursive CTE to get all the paths. This is the query I wrote:

USE msdb
-- SELECT * FROM dbo.sysmanagement_shared_server_groups_internal AS sssgi;
-- SELECT * FROM [msdb].[dbo].[sysmanagement_shared_registered_servers_internal];
WITH cte_groups (groupid, name, parentid, parentname, fullname)
AS (
SELECT g1.server_group_id,,
    CAST('' AS VARCHAR(100)) AS parentname,
    CAST( AS VARCHAR(200)) AS fullname
FROM dbo.sysmanagement_shared_server_groups_internal AS g1
WHERE g1.parent_id IS null
SELECT g2.server_group_id,,
    ( AS VARCHAR(100)) AS parentname,
    CAST( gr.fullname + '\' + AS VARCHAR(200)) AS fullname
FROM dbo.sysmanagement_shared_server_groups_internal AS g2
INNER JOIN cte_groups AS gr
ON gr.groupid = g2.parent_id
FROM cte_groups as cg