Check this query - Note that it will not cover all future cases probably but do answer your current data in the thread at this time
-- (1) This solution based on the assumption that the identifier is at the end of the string - not sure what you want to do in other cases
-- (2) To fit the new request "from the longest to the smallest" I check the length
-----------------------------------------
DECLARE @TName nvarchar(200)
--SET @TName = 'Ron, Lamor M. The Great' -- Test 01
SET @TName = 'fg dfs gfdg. Not The Great' -- Test 02
;With MyCTE AS (
select
--@TName,
TheValue = REPLACE(@TName,Identifier,''),
Identifier
, CI = CASE WHEN charindex(Identifier,@TName,1)>1 THEN 1 ELSE 0 END
, RN = ROW_NUMBER() OVER (
PARTITION BY CASE WHEN charindex(Identifier,@TName,1)>1 THEN 1 ELSE 0 END
ORDER BY CASE WHEN charindex(Identifier,@TName,1)>1 THEN 1 ELSE 0 END DESC,LEN(Identifier) DESC)
FROM (VALUES ('The Great'),('Not The Great'),('Small'),('Big')) T(Identifier) -- add all your preexisting phrases or use a table with all preexisting phrases
)
SELECT TOP 1 TheValue,Identifier--, CI,RN
FROM MyCTE
ORDER BY CI DESC,RN
GO
UPDATE 2022-04-23 19:17 Israel time
Following Erland comment, the next solution cover a case that there is no identifier at the end of the string - in this case it will return '' in the second column and the entire string in the first column of the result SET
DECLARE @TName nvarchar(200)
--SET @TName = 'Ron, Lamor M. The Great' -- Test 01
SET @TName = 'Big Swifty and Associates, Trendmongers' -- Test 02
;With MyCTE AS (
select
--@TName,
TheValue = REPLACE(@TName,Identifier,''),
Identifier
, CI = CASE WHEN charindex(Identifier,@TName + ' ',1)>1 THEN 1 ELSE 0 END
, RN = ROW_NUMBER() OVER (
PARTITION BY CASE WHEN charindex(Identifier,@TName,1)>1 THEN 1 ELSE 0 END
ORDER BY CASE WHEN charindex(Identifier,@TName,1)>1 THEN 1 ELSE 0 END DESC,LEN(Identifier) DESC)
FROM (VALUES (' '),('The Great'),('Not The Great'),('Small'),('Big')) T(Identifier) -- add all your preexisting phrases or use a table with all preexisting phrases
)
SELECT TOP 1
TheValue,Identifier--, CI,RN
FROM MyCTE
ORDER BY CI DESC,RN
GO