Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find references to other databases

In a SQL Server database I need to find all stored procedures and views containing references to other databases. (I'm required to replace them with synonyms.)

I have many stored procedures and I do not want to search them manually.

Any ideas how to find them easily?

like image 416
Petr Avatar asked May 14 '26 19:05

Petr


1 Answers

Depending on the version of SQL Server, you might also find value in this query:

SELECT OBJECT_SCHEMA_NAME(referencing_id), OBJECT_NAME(referencing_id) 
  FROM sys.sql_expression_dependencies
  WHERE referenced_database_name = 'YourDatabaseName';

In reality you'll need a combination of searching the views and procedures (as @M_M pointed out), this, and you'll potentially need to weed some out. For example sys.sql_modules will show false positives if your database name is a string that could appear naturally in your modules for other reasons. But this answer won't find the database name when it's embedded in dynamic SQL, for example.

like image 103
Aaron Bertrand Avatar answered May 19 '26 02:05

Aaron Bertrand