September 8, 2009 at 3:30 pm
Does anyone know how to identify composite primary keys in sql server view?
I mean, a table which contains this detail, for example:
TableA -> Primary Key (Id,name)
TableB -> PrimaryKey (id)
I'm going to pass the name of the column, (ID) and my query would return
"Table with unique primary key for column ID: TableA",
because the ID in TableB is composite.
I've tried do a query using sys.columns, sys.tables and sys.key_column_usage, but the
query always return the bothm TableA and TableB, I just need to filter this.
September 8, 2009 at 4:11 pm
There is more than one way. Here's one:
SELECT N'Table with unique primary key for column ID: ' +
SCHEMA_NAME(T.[schema_id]) + N'.' +
OBJECT_NAME(T.[object_id])
FROM sys.key_constraints KC
JOIN sys.index_columns IC
ON IC.[object_id] = KC.parent_object_id
AND IC.index_id = KC.unique_index_id
JOIN sys.columns C
ON C.[object_id] = KC.parent_object_id
AND C.column_id = IC.column_id
JOIN sys.tables T ON T.[object_id] = KC.parent_object_id
WHERE C.name = N'ID'
AND KC.[type] = N'PK'
AND INDEX_COL(SCHEMA_NAME(T.[schema_id]) + N'.' + OBJECT_NAME(T.[object_id]), IC.index_id, 2) IS NULL;
Neater versions almost certainly exist.
Paul White
SQLPerformance.com
SQLkiwi blog
@SQL_Kiwi
September 9, 2009 at 5:59 am
Many thanks man, I didn't know the view sys.key_constraints, it helped me a lot.
September 9, 2009 at 6:34 am
No worries, dude 😀
Paul White
SQLPerformance.com
SQLkiwi blog
@SQL_Kiwi
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply