UPDATE : SQL SERVER – 2005 – Find Tables With Foreign Key Constraint in Database
This is very long query. Optionally, we can limit the query to return results for one or more than one table.
SELECT
K_Table = FK.TABLE_NAME,
FK_Column = CU.COLUMN_NAME,
PK_Table = PK.TABLE_NAME,
PK_Column = PT.COLUMN_NAME,
Constraint_Name = C.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
SELECT i1.TABLE_NAME, i2.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT ON PT.TABLE_NAME = PK.TABLE_NAME
---- optional:
ORDER BY
1,2,3,4
WHERE PK.TABLE_NAME='something'WHERE FK.TABLE_NAME='something'
WHERE PK.TABLE_NAME IN ('one_thing', 'another')
WHERE FK.TABLE_NAME IN ('one_thing', 'another')
Reference : Pinal Dave (http://blog.SQLAuthority.com)




Excellenet Script
Perfect
REALLY HELPED ME.. GR8 SCRIPTING..
can there be multiple primary key (in multiple tables) in response to one foreign key in a table
Hi
Thanks for your query, it set me off in the right direction :).
Much Appreciated.
I have rewritten the query to be slightly faster:
SELECT
CONSTRAINT_NAME = REF_CONST.CONSTRAINT_NAME,
TABLE_CATALOG = FK.TABLE_CATALOG,
TABLE_SCHEMA = FK.TABLE_SCHEMA,
TABLE_NAME = FK.TABLE_NAME,
COLUMN_NAME = FK_COLS.COLUMN_NAME,
REFERENCED_TABLE_CATALOG = PK.TABLE_CATALOG,
REFERENCED_TABLE_SCHEMA = PK.TABLE_SCHEMA,
REFERENCED_TABLE_NAME = PK.TABLE_NAME,
REFERENCED_COLUMN_NAME = PK_COLS.COLUMN_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS REF_CONST
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
ON REF_CONST.CONSTRAINT_CATALOG = FK.CONSTRAINT_CATALOG
AND REF_CONST.CONSTRAINT_SCHEMA = FK.CONSTRAINT_SCHEMA
AND REF_CONST.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
AND FK.CONSTRAINT_TYPE = ‘FOREIGN KEY’
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON REF_CONST.UNIQUE_CONSTRAINT_CATALOG = PK.CONSTRAINT_CATALOG
AND REF_CONST.UNIQUE_CONSTRAINT_SCHEMA = PK.CONSTRAINT_SCHEMA
AND REF_CONST.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
AND PK.CONSTRAINT_TYPE = ‘PRIMARY KEY’
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE FK_COLS ON REF_CONST.CONSTRAINT_NAME = FK_COLS.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE PK_COLS ON PK.CONSTRAINT_NAME = PK_COLS.CONSTRAINT_NAME
Hope this helps :)
-Mark
Mark,
Thanks for sharing the information. It is important to learn and share. I am glad that you follow the same understanding.
Very good script.
Kind Regards,
Pinal
Hi Pinal,
Am a beginner in SQLServer and I find your script to be very helpful.
Do you have a similar script that lists all types of constraints, i.e. check constraints etc.?
Any pointers to the right direction will be very much appreciated.
Really fundoo, good that people like you believe in sharing information!
Hi Pinal,
I used this script to find duplicate relationships. Thank you for this information sharing.
Hey, this is really a good querry, We can use when we want to know that how many primary keys and forign keys are there in the database.
BUt as Subhash said that he used this querry to “find duplicate relationships” in the database.
Wht is mean by “duplicate relationships” ???
Hi,
What is the query used to display all tables names in sql server (Query analyzer) ?
Pls reply to this question? ASAP
thanks and regards
n.m.
Excellent, Very impressed
Hi there again
I was just re-looking at this script, and was wondering about something:
For the line in the script above that reads:
WHERE i1.CONSTRAINT_TYPE = ‘PRIMARY KEY’
Is this necessary, because don’t all foreign key constraints correspond to Primary Keys? In the REFERENTIAL_CONSTRAINTS table, the FK columns correspond to UNIQUE_CONSTRAINT…. columns. Can a FK correspond to any unique constraint or only a Primary Key constraint?
Thanks
Sorry, just to clarify the above comment:
The above mentioned where clause in your SQL is deftinately necessary because of the nested select statement.
Removing the CONSTRAINT_TYPE clause in my script above will not make it any faster.
I am just wondering what applies conceptually :)
hi every one
Thank you alot i am a bigenier in developing software
i want your advice to help me go in this field
Nice! However, I don’t think it’s working properly on multi-column foreign keys.
This is not a comment rather question.
I went through the above post and found very interesting. I tried to modify it according to my problem but no luck.
Problem.
how to get the list of tables who has the FK relation ship with the given tables. once i get the list I want to delete the record from the parent table and set the references to null from the table where parents pk is referred as fk.
I am not using cascade delete since I don’t want to delete the complete row.
right now i am doing this by writing the simple SP and manually setting the null to the referenced tables.
Thanks you very much in advance.
-Santosh Maskar
after spending some time on the given SQL I solved my problem.
Thanks a lot
-Santosh
hi
I need to delete the paticular records from parent table without affecting the child table(will have more child table) and also the relationship between the records should be removed,
since am going to use the unaffected record in child table as parent table..
Hope u got it..
Your help is appreciated.
Thanks & Regards
Bala
Thank for the script. It really help me.
Thank
Regards.
Johnson
This was a great tutorial! It was no problem at all to adapt this and create a routine that automatically fixed that pesky name mangling the occurs in Sql Server constraints ( so that FK__Trader__departme__4B7734FF becomes FK__Trader__department_id).
You helped me solve a real headache.
Really Nice Article… helped me alot :)
This is good but if I have multiple columns in my foreign keys it will multiply the results so that 2 column returns 4 rows of data and 3->9 and so on.
Adding the following line to Marks solution will reduce the amount of lines
AND FK_COLS.ORDINAL_POSITION = PK_COLS.ORDINAL_POSITION
Otherwise this was really helpful.
Hi all,
Great script, really helpful. I was wondering, is there a way i can change this script so that I can get a sensible order of integrity?
Basically my problem is that we have this ’sync’ service that packages data up from remote sites and sends it to our central database. At the moment it just pipes all the data in an manual order that we set because we know about the constraints. What i would like is to be able to know which tables need to have their data first (ie tables that have their primary keys referenced as foreign keys in other tables).
Is there a way to do that?
I needed a script which find all the table where primary key of a table is used in other tables as foreign key. i need to delete a record in master table ..
This script worked well for me.
thanks
suppose i have number of select statements in a single sp in sqlserver 2005.
i need to know how many statements are there in that sp.
hi…
i want to delete rows from tables having “UserID” Coulmn in a databse named “Test” . but some tables are foreignkey constraints… how it can be done…
first i have to find all tables having UserID column. then delete the rows from tables containg foreign key constraint(i.e where UserID=’SOMETHING’)…after that delete the tables having primary key..in a database…
SUMMARY:: I HAVE TO CLEAR ALL THE ROWS FROM ALL THE TABLES HAVING USERID COLUMN IN A DATABASE WHERE SOME ARE FOREGNKEY CONSTRAINTS AND SOME ARE PRIMARY KEY…
HOW IT’S POSSIBLE…
Hey How about
EXEC SP_Fkeys @TableName
Could we bind same default to multiple columns of the same table. If so then how.
PINAL, I have a somewhat related problem that i was wondering if you had a solution for
There are 4 tables with relationships to each other. ConferenceRoom, ConferenceRoomCapacity, TeleTrackPhone, and RPSLocation
The table ConferenceRoom stores attributes pertaining to conference rooms.
The table ConferenceRoomCapacity stores attributes pertaining to the maximum capacity of the conference room.
The table TeleTrackPhone contains different phone numbers. It stores ConferenceRoomID and RPSLocationID as FKs.
The table RPSLocation stoes info about different locations, city, state, etc.
The TeleTrackPhone table allows duplicate values for the ConferenceRoomID because a conference room can have more than one phone number.
This is the query that I run.
SELECT DISTINCT A.ConferenceRoomID, A.ConferenceRoomName, C.City, C.State
FROM ConferenceRoom As A, TeleTrackPhone As B, RPSLocation As C, ConferenceRoomCapacity As D
WHERE A.ConferenceRoomID = B.ConferenceRoomID
AND B.RPSLocationID = C.RPSLocationID
AND A.ConferenceRoomID = D.ConferenceRoomID
My problem is that it returns duplicates if the conference room has multiple phone numbers and i only want the query to return a list of conference rooms.
Nice one… It helped me to a lot during SQL Server Replication Setup
Hello,
This one is simpler, just gives you table_name and which type of key information and key name.
select OBJECT_NAME(PARENT_OBJ) TABLE_NAME, CASE WHEN XTYPE =’F’ THEN ‘FORIEGN KEY’ ELSE ‘PRIMARY KEY’ END KEY_TYPE , NAME KEY_NAME
from sysobjects where Xtype in (’F’ , ‘pK’) ORDER BY XTYPE DESC
I am using only sysobjects table to get this information.
Hope this helps.
Imran.
Fantastic script, thank you so much!
Hi,
here’s another version (mine :-; ) to extract foreign keys.
Replace ‘TABLE_NAME’ with yours … !
Regards
Karim Laurent
select OBJECT_NAME(FKEYS.PARENT_OBJECT_ID) source ,PKCOLUMN_NAME= convert(sysname,col1.name), OBJECT_NAME(FKEYS.referenced_object_id) destination, FKCOLUMN_NAME = convert(sysname,COL2.name)
from
sys.columns COL1,
sys.columns COL2,
sys.foreign_keys FKEYS
inner join sys.foreign_key_columns KEY_COLUMN on (KEY_COLUMN.constraint_object_id = FKEYS.object_id)
where
COL1.object_id = FKEYS.referenced_object_id
AND COL2.object_id = FKEYS.parent_object_id
AND COL1.column_id = KEY_COLUMN.referenced_column_id
AND COL2.column_id = KEY_COLUMN.parent_column_id
AND OBJECT_NAME(FKEYS.PARENT_OBJECT_ID)=’TABLE_NAME’
Thanks, Great scripting
MAKE IT MORE SHORT N SIMPLE
Will work on both 2000 and 2005
===========================
select object_name(constid) FKey_Name, object_name(fkeyid) Child_Table, c1.name FKey_Col,
object_name(rkeyid) Parent_Table, c2.name Ref_KeyCol
from sysforeignkeys s
inner join syscolumns c1
on ( s.fkeyid = c1.id
and s.fkey = c1.colid )
inner join syscolumns c2
on ( s.rkeyid = c2.id
and s.rkey = c2.colid )
Nice ..the script really helped me..!
Thanks..!
I want to retrieve only limited data from database like limit is keyword in mysql which retrieve limited data according to our arguments. Like I want to load only 10 records from the database at first display in page. but I don’t want to using top. Because its create problem of paging. So please give me alternate solution for that’d have use row index but in that row index I have to write inner query and my data base I s to heavy.
Excellent script that got me going in the right direction. Thank you so much.
Excellent script thank you
excelente, gracias por publicarlo.
Hi,
It was great, it helped me in finding the duplicate FK for the same set of tables for the same set of fields.
With Regards
Dakshina Murthy
Hi
How to retrieve all columns of the given table and its foreign key table.
Regards
Jaseem, A.