I\'m trying to find all references to an object in an SQL Server database.
How can I quickly search? SQL Server Management Studio does not seem to do it. I use http:
Use:
select object_name(m.object_id), m.*
from sys.sql_modules m
where m.definition like N'%name_of_object%'
...because SYSCOMMENTS
and INFORMATION_SCHEMA.routines
have nvarchar(4000) columns. So if "name_of_object" is used at position 3998, it won't be found. SYSCOMMENTS
does have multiple lines, but INFORMATION_SCHEMA.routines
truncates.
Very late to the party, but...
You can use the system proc sys.sp_depends
:
exec sys.sp_depends 'object_name'
The result is a table listing all of the database objects that depend on (i.e., reference) object_name
. Each row contains the name and type of the referring object, along with other info columns, depending on the type of object_name
.
Note: This proc was added in MS SQL Server 2008.
See: MSDN docs
The docs say that this proc may be removed in a future release, and to use sys.dm_sql_referencing_entities instead, but it's still alive and kicking in MS SQL 2017.
In SQL Server 2000 here is a query that can search inside object definitions, supporting search strings of up to 2000 characters. It uses the chunks in the syscomments
table.
SELECT O.name, O.xtype
FROM sysobjects O
WHERE EXISTS (
SELECT *
FROM
(
SELECT
Chunk = Substring(C1.text, T.Offset, 4000)
+ Coalesce(Substring(C2.text, 1, T.AdditionalLength), '')
FROM
syscomments C1
CROSS JOIN (
SELECT 1, 0
UNION ALL
SELECT 2001, 2000
) T (Offset, AdditionalLength)
LEFT JOIN syscomments C2
ON C1.id = C2.id
AND C1.colid + 1 = C2.colid
AND T.Offset > 1
WHERE
O.id = C1.id
) C
WHERE
Chunk LIKE '%search string%'
);
I use this query to look for all tables (or text) in the stored procedures:
SELECT DISTINCT o.name, o.xtype
FROM syscomments c
INNER JOIN sysobjects o ON c.id=o.id
WHERE c.TEXT LIKE '%tablename%'