Skip to content

Instantly share code, notes, and snippets.

@ardacetinkaya
Last active April 28, 2019 22:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ardacetinkaya/865dffe144b032b6ed459bb628c45e06 to your computer and use it in GitHub Desktop.
Save ardacetinkaya/865dffe144b032b6ed459bb628c45e06 to your computer and use it in GitHub Desktop.
Simple SQL to find tables that are used in a stored procedure. #mssql #sql #sqlserver #storedprocedure
DECLARE @temptableforSP TABLE (spName varchar(100), tableName nvarchar(100))
DECLARE @SP_Name as NVARCHAR(100);
DECLARE @SP_Cursor as CURSOR;
SET @SP_Cursor = CURSOR FOR
SELECT [name] FROM sys.objects WHERE name LIKE 'sp%' AND type='P' -- Gets SPs for specific names
OPEN @SP_Cursor;
FETCH NEXT FROM @SP_Cursor INTO @SP_Name;
WHILE @@FETCH_STATUS = 0
BEGIN
--print(@SP_Name)
INSERT INTO @temptableforSP
SELECT
OBJECT_NAME(referencing_id) AS referencing_entity_name,
referenced_entity_name
FROM sys.sql_expression_dependencies AS sed
INNER JOIN sys.objects AS o ON sed.referencing_id = o.object_id
WHERE referencing_id = OBJECT_ID(@SP_Name);
FETCH NEXT FROM @SP_Cursor INTO @SP_Name;
END
CLOSE @SP_Cursor;
DEALLOCATE @SP_Cursor;
-------Display temp. table for SP and Table relation
SELECT * FROM @temptableforSP
------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment