I need to output the constraint information for a given table. I've found lots of closely relevant information here at SO, but I'm not finding a couple of specific pieces of information.
I need the output to look like this in the query results:
CONSTRAINT_NAME CONSTRAINT_TYPE COLUMN_NAME REFERENCED_TABLE REFERENCED_COLUMN
Currently, I have this query:
SELECT
obj_Constraint.NAME AS CONSTRAINT_NAME,
obj_Constraint.type_desc AS CONSTRAINT_TYPE,
'' AS COLUMN_NAME,
'' AS REFERENCED_TABLE,
columns.NAME AS REFERENCED_COLUMN
FROM sys.objects AS obj_table
LEFT JOIN sys.objects AS obj_Constraint ON obj_table.object_id = obj_Constraint.parent_object_id
LEFT JOIN sys.sysconstraints AS constraints ON constraints.constid = obj_Constraint.object_id
LEFT JOIN sys.columns AS columns ON columns.object_id = obj_table.object_id AND columns.column_id = constraints.colid
WHERE obj_table.name = 'some_table'
ORDER BY obj_Constraint.type_desc
Where do I get the referenced (foreign key) table and column information from?
(I'd need a query compatible for SQL Server versions 2008 & later)
EDIT
Based on initial responses, I may not have been clear on the desired output.
Say I have a table "people" with columns "poepleID", "name", "city", "stateID". The Primary Key is on the poepleID column. I also have a table "states" with "stateID" and "state". The Primary Key on that is on the stateID column. You can guess that I have a Foreign Key constraint on people.stateID. I'll call that FK__people__states__stateID
So I need a query that will output this:
CONSTRAINT_NAME CONSTRAINT_TYPE COLUMN_NAME REFERENCED_TABLE REFERENCED_COLUMN
PK__people PRIMARY_KEY_CONSTRAINT peopleID
FK__people__states__stateID FOREIGN_KEY_CONSTRAINT stateID states stateID
I need to list all key constraints (primary, foreign - any) on the table in question ("people" in this case).