A few years ago, I needed to find a query that I had written in a SQL Stored Procedure but after clicking through several of them and striking out, I decided that there had to be a better way. I ended up writing a simple Stored Procedure with a single search parameter that would return a stored procedure definition and excerpt from it. I like it so much that I’ve added it to every database I’ve managed since then. It was a quick and dirty solution to a problem and I never really put much more thought into it - until tonight.
I was on the Windows Admins Slack tonight working on some SQL queries in the SCCM/ConfigMgr database with Riley Childs and Cody Mathis and during the course of the conversation, Cody shared a short query to find columns with a specific name in the database which got me thinking about my Stored Procedure. I took a look at what I was using and realized that we were in the same book, just on different pages. I took a few minutes and combined our logic and added a few extra bits to make a nicer version of the query. It will now return Table, View, Stored Procedure, and Function names where the object name, column name or object definition match your search criteria. It’s simple but effective. Hope you find it useful as well.
The Script
I’ve added it to my GitHub repo, which I will update as needed, or you can grab the code below:
--Change the USING to the DB you want to run this against.USE [CM_ASD]
--Change the value to your search term
DECLARE@Textnvarchar(1000)SET@Text='TextToFind'----Main Query--
DECLARE@newTextvarchar(1000)SET@NewText='%'+@Text+'%'SELECTDISTINCT'TableOrView'AS'ObjectType',TABLE_NAMEAS'ObjectName',CASEWHENCOLUMN_NAMELIKE@NewTextTHENCOLUMN_NAMEELSENULLENDAS'ColumnName',NULLAS'Excerpt',NULLAS'Definition'FROMINFORMATION_SCHEMA.COLUMNSWHERETABLE_NAMELIKE@NewTextORCOLUMN_NAMELIKE@NewTextUNIONSELECTDISTINCT'StoredProcedure'AS'ObjectType',SPECIFIC_NAMEAS'ObjectName',NULLAS'ColumnName',SUBSTRING(ROUTINE_DEFINITION,CHARINDEX(@Text,ROUTINE_DEFINITION)-50,100)AS'Excerpt',ROUTINE_DEFINITIONAS'Definition'FROMINFORMATION_SCHEMA.ROUTINESWHERESPECIFIC_NAMELIKE@NewTextORROUTINE_DEFINITIONLIKE@NewTextUNIONSELECTDISTINCT'ViewDefinition'AS'ObjectType',TABLE_NAMEAS'ObjectName',NULLAS'ColumnName',SUBSTRING(VIEW_DEFINITION,CHARINDEX(@text,VIEW_DEFINITION)-50,100)as'Excerpt',VIEW_DEFINITIONAS'Definition'FROMINFORMATION_SCHEMA.VIEWSWHERETABLE_NAMELIKE@NewTextORVIEW_DEFINITIONLIKE@newTextUNIONSELECTDISTINCT'Function'AS'ObjectType',TABLE_NAMEAS'ObjectName',COLUMN_NAMEAS'ColumnName',NULLAS'Excerpt',NULLAS'Definition'FROMINFORMATION_SCHEMA.ROUTINE_COLUMNSWHERECOLUMN_NAMELIKE@newTextORDERBYObjectType,ColumnName,ObjectName
Sample Output
Also, if you’re looking for something more robust that can search within the database data itself (plus much more), check out ApexSQL Search. I just started using it a few weeks ago and it really is fantastic. Best of all, it’s FREE, along with several other tools that I plan to try at some point.