Revision #1

You are currently reviewing an older revision of this page.
Go to current version

This script was developed to answer the question in this thread - http://social.msdn.microsoft.com/Forums/sqlserver/en-US/b25fd6ea-1f7c-43d0-ae18-d05ba368478c/i-need-query-find-all-the-sps-that-used-dynamic-sql

We can execute dynamic sql using sp_executesql or just with Exec / Execute .

To find the names of the StoredProcedure that has used dynamic SQL , below script can be used :

SELECT Schema_name(Schema_id)+'.'+Object_Name(M.Object_id) StoredProceduresWithDynamicSQL 
FROM sys.sql_modules M 
JOIN  sys.objects O ON M.object_id = O.object_id 
WHERE definition LIKE '%CREATE PROC%' 
AND (definition LIKE '%SP_ExecuteSQL%' OR definition LIKE '%EXEC%')

But Exec / Execute can be used  inside a Stored procedure to call another Stored procedure or to execute a dynamic sql , So to eliminate the Stored procedure referencing another  Stored procedure and to  find the names of the StoredProcedure that has used Exec / Execute only to execute dynamic SQL  ,
below script can be used :

SELECT Schema_name(Schema_id)+'.'+Object_Name(M.Object_id) StoredProceduresWithDynamicSQL 
FROM sys.sql_modules M 
JOIN  sys.objects O ON M.object_id = O.object_id 
WHERE definition LIKE '%CREATE PROC%' 
AND (definition LIKE '%SP_ExecuteSQL%' OR definition LIKE '%EXEC%'
EXCEPT
SELECT StoredProcedure  FROM
SELECT Schema_name(Schema_id)+'.'+Object_Name(M.Object_id) StoredProcedure 
FROM sys.sql_modules M 
JOIN  sys.objects O ON M.object_id = O.object_id 
WHERE definition LIKE '%CREATE PROC%' 
AND (definition LIKE '%SP_ExecuteSQL%' OR definition LIKE '%EXEC%')) tmp 
CROSS APPLY sys.dm_sql_referenced_entities (StoredProcedure, 'OBJECT');

The above script will not work under these scenarios , if we have used Exec / Execute  inside a stored procedure for both purposes i.e to call another stored procedure and to execute a dynamic SQL and the other scenario will be , if we have used sp_executesql or Exec / Execute  and commented it inside a Stored procedure ,
but still the above scripts will be useful because we don't have any other direct way to find the names of the Stored Procedure that has used dynamic SQL .
Revert to this revision