Created
March 20, 2023 05:20
-
-
Save hakanak/6efef81d0e8468b4da53ff75be6f477f to your computer and use it in GitHub Desktop.
MS SQL Server'da prosedür ile iç içe tabloları listelemek
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE PROCEDURE RecursiveTableList | |
@ParentID INT = NULL, | |
@Indent NVARCHAR(100) = '' | |
AS | |
BEGIN | |
SET NOCOUNT ON; | |
DECLARE @SQL NVARCHAR(MAX); | |
SET @SQL = ' | |
SELECT | |
' + @Indent + 'c.name as ChildTableName, | |
' + @Indent + 'p.name as ParentTableName | |
FROM | |
sys.foreign_keys as f | |
INNER JOIN sys.objects as p ON f.parent_object_id = p.object_id | |
INNER JOIN sys.objects as c ON f.referenced_object_id = c.object_id | |
WHERE | |
f.parent_object_id = ' + CAST(@ParentID AS NVARCHAR) + ' | |
'; | |
PRINT @SQL; | |
EXECUTE sp_executesql @SQL; | |
DECLARE @ChildID INT; | |
DECLARE child_cursor CURSOR FOR | |
SELECT object_id FROM sys.objects WHERE type = 'U' AND object_id != @ParentID; | |
OPEN child_cursor; | |
FETCH NEXT FROM child_cursor INTO @ChildID; | |
WHILE @@FETCH_STATUS = 0 | |
BEGIN | |
EXEC RecursiveTableList @ChildID, @Indent + ' '; | |
FETCH NEXT FROM child_cursor INTO @ChildID; | |
END; | |
CLOSE child_cursor; | |
DEALLOCATE child_cursor; | |
END; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment