Today I needed to find a way to alter a bunch of stored procedures and views that where using linkedserver objects. Those linked sever objects became obsolete because we consolidate a couple of instances to one instance. I used RedGate search to find the databases where the linkedserver objects where used. And with this peace of TSQL I removed the linked server objects from the stored procedures and views.
USE <database> GO declare @SearchString nvarchar(100) = '[linkedserver].' declare @ReplaceString varchar(100) = '' SELECT ObjectType = 'STORED PROCEDURE' ,name ,(OBJECT_DEFINITION(OBJECT_ID)) as OriginalObject ,replace (replace (OBJECT_DEFINITION(OBJECT_ID) ,'CREATE PROCEDURE','ALTER PROCEDURE') ,@SearchString,@ReplaceString) +char(10)+'GO' as ModifiedObject FROM sys.procedures WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%'+@SearchString+'%' escape '[' SELECT ObjectType = 'VIEW' ,name ,(OBJECT_DEFINITION(OBJECT_ID)) as OriginalObject ,replace (replace (OBJECT_DEFINITION(OBJECT_ID) ,'CREATE VIEW','ALTER VIEW') ,@SearchString,@ReplaceString) +char(10)+'GO' as ModifiedObject FROM sys.views WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%'+@SearchString+'%' escape '['