Quick one today:
Occasionally, when playing with metadata, we find ourselves in need to get Stored Procedures definition. For example, when you need to find all the procedures that call a particular table (or a synonym). Yes, there are other ways to gather this data, but doing the same with T-SQL is more fun and given refined controls.
Query objects using object name (but not table name):
Example:
--
-- Query objects using object name (but not table name)
--
SELECT O.object_id, O.name, O.type_desc, M.definition
FROM sys.objects AS O
LEFT OUTER JOIN sys.sql_modules AS M
ON M.object_id = O.object_id
WHERE O.name LIKE '%Object_Name%'
OR O.name LIKE '%Object_Name_but_not_table_name%'
GO
Query objects using any object name, including table name:
--
-- Query objects using any object name in the definition (including table name)
--
SELECT O.object_id, O.name, O.type_desc, M.definition
FROM sys.objects AS O
LEFT OUTER JOIN sys.sql_modules AS M
ON M.object_id = O.object_id
WHERE M.definition LIKE '%ViewName%'
OR M.definition LIKE '%TableName[.]%'
GO
Cool thing is, this system table sys.sql_modules has definition for more objects :
- Stored Procedures
- DML Triggers
- Scalar Functions
- Table Valued Functions
- Replication-filter-procedure
- Views
- Rules
Read Full Post »