WITH RankedGraphs AS (SELECT WorkspaceId,
                             GraphId,
                             Version,
                             State,
                             Name,
                             Description,
                             GraphJson,
                             PoliciesJson,
                             MetadataJson,
                             SubmittedAt,
                             SubmittedBy,
                             PublishedAt,
                             PublishedBy,
                             PublishNotes,
                             CreatedAt,
                             UpdatedAt,
                             CreatedBy,
                             UpdatedBy,
                             ROW_NUMBER() OVER (PARTITION BY WorkspaceId, GraphId ORDER BY Version DESC) AS RowNum
                      FROM [dbo].[OrchestrationGraphs]
WHERE WorkspaceId = @WorkspaceId)
SELECT WorkspaceId,
       GraphId,
       Version,
       State,
       Name,
       Description,
       GraphJson,
       PoliciesJson,
       MetadataJson,
       SubmittedAt,
       SubmittedBy,
       PublishedAt,
       PublishedBy,
       PublishNotes,
       CreatedAt,
       UpdatedAt,
       CreatedBy,
       UpdatedBy
FROM RankedGraphs
WHERE RowNum = 1
ORDER BY Name;
