I have some SQL that gets a few details about a table.
SELECT Column_Name, Is_Nullable, Data_Type, Character_Maximum_Length
FROM Information_Schema.Columns
WHERE Table_Name='GenSchool'
This is working ok so far and returns a row per column in the table. What I want however, is for it to also return some Foreign Key details too. For example, GenSchool has a column SchoolType which has a FK to GenSchoolType.Code.
As well as the columns selected above, I need the query to return the FK table and column name of linked table or NULL where the column doesn’t have a FK.
This is returned from the query above.
Code NO nvarchar 10
CodeDescription YES nvarchar 80
Deleted NO bit NULL
Type NO nvarchar 20
And I’d like it to return something like
Code NO nvarchar 10 NULL NULL
CodeDescription YES nvarchar 80 NULL NULL
Deleted NO bit NULL NULL NULL
Type NO nvarchar 20 GenSchoolType Code
I’ve been trying for ages using inner joins on sys tables but I’m not getting anywhere. If you need me to show what I’ve tried I can.
Thank you in advance.
So I finally worked out the solution.
This returns a row per column in the database with the following data
Feel free to use this if it meets your needs.