Peter J Quinn
Peter J Quinn

Reputation: 69

Removing all reference to a linked server on SQL Server 2008 R2

I've been charged with the task of moving a database from ServerA to ServerB. ServerB contains many other database objects, a fair few using a Linked Server connection to ServerA. For example, there may be a view which joins a table1 on ServerB to ServerA.database.schema.table1

Does anyone know of a script I can run on ServerB that will display a list of all objects that reference ServerA, so that I may update them quickly, without having to open each object.

I hope this makes sense. Thanks

Upvotes: 0

Views: 792

Answers (1)

Aaron Bertrand
Aaron Bertrand

Reputation: 280351

This has the potential for false positives, but that is probably better than relying on dependency views (which will miss dynamic SQL or simply out-of-date dependencies):

SELECT 'EXEC sp_helptext ''' 
 + QUOTENAME(OBJECT_SCHEMA_NAME([object_id]))
 + '.' + QUOTENAME(OBJECT_NAME([object_id])) + ''';'
FROM sys.sql_modules
WHERE definition LIKE '%ServerA.%';

You may also need to account for potential cases where the server name is enclosed in square brackets:

OR definition LIKE '%\[ServerA\].%' ESCAPE '\';

You should also consider using SYNONYMs to prevent this type of maintenance in the future. In fact you may also want to check for any synonyms that reference the server name:

SELECT name, base_object_name
  FROM sys.synonyms
  WHERE base_object_name LIKE 'ServerA.%'
  OR base_object_name LIKE '\[ServerA\].%' ESCAPE '\';

Upvotes: 4

Related Questions