Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Come determinare la chiave primaria per una tabella in SQL Server?

Lo uso in un generatore di codice che ho scritto per ottenere la chiave primaria:

SELECT i.name AS IndexName, 
    OBJECT_NAME(ic.OBJECT_ID) AS TableName, 
    COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName, 
    c.is_identity, c.user_type_id, CAST(c.max_length AS int) AS max_length, 
    CAST(c.precision AS int) AS precision, CAST(c.scale AS int) AS scale 
FROM sys.indexes AS i 
INNER JOIN sys.index_columns AS ic 
INNER JOIN sys.columns AS c ON ic.object_id = c.object_id AND ic.column_id = c.column_id 
    ON i.OBJECT_ID = ic.OBJECT_ID AND i.index_id = ic.index_id 
WHERE i.is_primary_key = 1 AND ic.OBJECT_ID = OBJECT_ID('dbo.YourTableNameHere')
ORDER BY OBJECT_NAME(ic.OBJECT_ID), ic.key_ordinal