Question

How can I find all views and SP's that contains UNION keyword?

(Alternate question: in what system table is stored the text of SP's and Views)

Thank you

Was it helpful?

Solution

Here is a somewhat naive but workable example: (tested on SQL Server 2005 & 2008 R2)

use msdb;

SElECT * FROM sys.all_sql_modules
WHERE  
(definition LIKE '%CREATE VIEW%' OR 
 definition LIKE '%CREATE PROCEDURE%')
AND definition LIKE '%UNION%'

To solidify it just join via the object_id link and filter for views and stored procs by object type rather than using LIKE.

Simpler:

SElECT * FROM sys.all_sql_modules
WHERE definition LIKE '%UNION%'

Caveat: Since we're performing a LIKE comparison against the create script of each object we will also pick up on the word UNION if/when it appears in comments. That might be OK for you but if you need to results to be more deterministic and avoid such cases your WHERE clause will need to be more complex, possibly using regex to refine the results.

OTHER TIPS

Personally I like using the INFORMATION_SCHEMA views:

For stored procedures:

SELECT 
    * 
FROM 
    INFORMATION_SCHEMA.ROUTINES 
WHERE 
    ROUTINE_TYPE = 'PROCEDURE' 
    AND 
    --ROUTINE_DEFINITION LIKE '%union%' <-- 4,000 character limitation
    OBJECT_DEFINITION(OBJECT_ID(SPECIFIC_SCHEMA + '.' + SPECIFIC_NAME)) 
        LIKE '%union%'

And for views:

SELECT 
    * 
FROM 
    INFORMATION_SCHEMA.VIEWS 
WHERE 
    --VIEW_DEFINITION LIKE '%union%' <-- 4,000 character limitation
    OBJECT_DEFINITION(OBJECT_ID(TABLE_SCHEMA + '.' + TABLE_NAME)) LIKE '%union%'

These views are limited to definitions in whichever database you're currently USEing.

Alternatively, there is a wonderful tool from xSQL software that gives you powerful searching capabilities for Microsoft SQL Server 2005 and 2008.

UPDATE: As @Bogdan pointed out, the INFORMATION_SCHEMA definitions are limited to the first 4000 characters. I've updated my answer to include a workaround. At this point it may just be easier to go after the sys views.

Those things are stored in sys.sql_modules.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top