Skip to content
Advertisement

How to find a specific Foreign Key of a table through T-SQL?

i want to bring ONE foreign key from several ones in a table. in the GUI interface in sql server if we expand the table options we can see a folder called “Keys”, in this folder there is one primary key and several foreign ones. In my example i have three tables, Customer, Orders and Items. Customer has Customer_ID as primary, Items has Item_ID as primary and Orders has Order_ID as primary, foreign key Customer_nbr references customer (Customer_ID) and foreign key item_nbr references Items (Item_ID).

so in that “Keys” folder there are names for those keys like: “FK_Orders_Customer__38996AB5″

the problem is that the number “38996AB5” that follows the customer word is not fixed, if you delete constraints then re-establish them it will be changed (for security reasons or so).

so i am looking for an SQL command that can be typed in order to get that key no matter what it was like. logically i could use the keyword “LIKE” (i.e. … like = ‘FK_Orders_Customer__%’) but i could not know how or where to put it.

thanks in advance.

Advertisement

Answer

Use:

SELECT *
FROM sys.foreign_keys
WHERE name LIKE '%yourForeignKeyName%'
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement