Showing posts with label How can I list all foreign keys referencing a given. Show all posts
Showing posts with label How can I list all foreign keys referencing a given. Show all posts

to get table names which are referenced by given table

Use this function to get table name which are referenced as foreign key by  given table's primary key

I want to find out that table names in database, a primary key of a table that referenced foreign key of another tables.

Here i have to pass the main table name and find out the tables the primary key of main table referenced the foreign key of another tables.


CREATE FUNCTION [dbo].[getForignkeyTblName1](@tblname varchar(50))
RETURNS @tbl TABLE(tblnames varchar(50))
AS
BEGIN
declare @objid int,@objname nvarchar(776),@result varchar(50)
INSERT INTO @tbl SELECT b.Name FROM sys.foreign_keys a
INNER JOIN sys.tables b
ON a.parent_object_id =b.object_id
 WHERE a.referenced_object_id =(SELECT object_id FROM  sys.tables WHERE name=@tblname)
return
END

--SELECT * FROM [getForignkeyTblName1]('MainTable')