Within my rather large database, I would like to find out everywhere a column is referenced within the entire schema (SPs, functions, tables, triggers...). I don't want to just do a text search since this will pick up comments and also will find similarly named columns from other tables.
Does anyone know if/how I can do this? I use SQL Server 2008.
The most Simplest one is by using sys. foreign_keys_columns in SQL. Here the table contains the Object ids of all the foreign keys wrt their Referenced column ID Referenced Table ID as well as the Referencing Columns and Tables.
Using SQL Server Management StudioIn Object Explorer, expand Databases, expand a database, and then expand Tables. Right-click a table, and then click View Dependencies.
Warning: Even though this is a text-search method, the script I'm going to share has saved me lots and lots of hours. It searches inside:
I needed to specify a collation to make it work for me.
SELECT sys.objects.object_id, sys.schemas.name AS [Schema], sys.objects.name AS Object_Name, sys.objects.type_desc AS [Type] FROM sys.sql_modules (NOLOCK) INNER JOIN sys.objects (NOLOCK) ON sys.sql_modules.object_id = sys.objects.object_id INNER JOIN sys.schemas (NOLOCK) ON sys.objects.schema_id = sys.schemas.schema_id WHERE sys.sql_modules.definition COLLATE SQL_Latin1_General_CP1_CI_AS LIKE '%{Column Name}%' ESCAPE '\' ORDER BY sys.objects.type_desc, sys.schemas.name, sys.objects.name
The output is like the following:
Update: If you need to search for a certain table, SP, etc. you could use a more specialized query:
DECLARE @SCHEMA_NAME VARCHAR(100) = 'dbo'; DECLARE @OBJECT_NAME VARCHAR(100) = 'MY_OBJECT'; SELECT sys.objects.object_id, sys.schemas.name AS [Schema], sys.objects.name AS Object_Name, sys.objects.type_desc AS [Type] FROM sys.sql_modules (NOLOCK) INNER JOIN sys.objects (NOLOCK) ON sys.sql_modules.object_id = sys.objects.object_id INNER JOIN sys.schemas (NOLOCK) ON sys.objects.schema_id = sys.schemas.schema_id WHERE ( '#' + sys.sql_modules.definition + '#' COLLATE SQL_Latin1_General_CP1_CI_AS LIKE '%[^a-z_]'+@SCHEMA_NAME+'.'+@OBJECT_NAME+'[^a-z_]%' ESCAPE '\' OR '#' + sys.sql_modules.definition + '#' COLLATE SQL_Latin1_General_CP1_CI_AS LIKE '%[^a-z_]\['+@SCHEMA_NAME+'\].'+@OBJECT_NAME+'[^a-z_]%' ESCAPE '\' OR '#' + sys.sql_modules.definition + '#' COLLATE SQL_Latin1_General_CP1_CI_AS LIKE '%[^a-z_]'+@SCHEMA_NAME+'.\['+@OBJECT_NAME+'\][^a-z_]%' ESCAPE '\' OR '#' + sys.sql_modules.definition + '#' COLLATE SQL_Latin1_General_CP1_CI_AS LIKE '%[^a-z_]\['+@SCHEMA_NAME+'\].\['+@OBJECT_NAME+'\][^a-z_]%' ESCAPE '\' ) ORDER BY sys.objects.type_desc, sys.schemas.name, sys.objects.name
P.S.: Both queries search inside comments too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With