views:

111

answers:

7

I want to get a particular table's primary key using SQL query for SQL Server database.

In MySQL I am using following query to get table primary key:

SHOW KEYS FROM tablename WHERE Key_name = 'PRIMARY'

What is equivalent of above query for SQL Server ?.

If There is a query that will work for both MySQL and SQL Server then It will be an ideal case.

Thanks

+1  A: 

From memory, its either this

SELECT * FROM sys.ojbects
WHERE type = 'PK' 
AND  object_id = OBJECT_ID ('tableName')

or this..

SELECT * FROM sys.ojbects
WHERE type = 'PK' 
AND  parent_object_id = OBJECT_ID ('tableName')

i think one of them should probably work depending on how the data is stored but i am afraid i have no access to SQL to actually verify the same

InSane
+3  A: 

Using SQL SERVER 2005, you can try

SELECT  i.name AS IndexName,
        OBJECT_NAME(ic.OBJECT_ID) AS TableName,
        COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName
FROM    sys.indexes AS i INNER JOIN 
        sys.index_columns AS ic ON  i.OBJECT_ID = ic.OBJECT_ID
                                AND i.index_id = ic.index_id
WHERE   i.is_primary_key = 1

Found at SQL SERVER – 2005 – Find Tables With Primary Key Constraint in Database

astander
Where will place my desired table name(Primary key required for ) in above query ?
Awan
+2  A: 
select * 
from sysobjects 
where xtype='pk' and 
   parent_obj in (select id from sysobjects where name='tablename')

this will work in sql 2005

Harendra
If you post code or XML, **please** highlight those lines in the text editor and click on the "code" button (101 010) on the editor toolbar to nicely format and syntax highlight it!
marc_s
Also, in SQL Server 2005 and up, it's recommended to use the `sys` catalog views and stop using the legacy `sysobjects` table. So in your case, use `sys.tables` and `sys.columns` and other sys catalog views.
marc_s
+1  A: 

The code I'll give you works and retrieves not only keys, but a lot of data from a table in SQL Server. Is tested in SQL Server 2k5/2k8, dunno about 2k. Enjoy!

SELECT DISTINCT
    sys.tables.object_id AS TableId,
    sys.columns.column_id AS ColumnId,
    sys.columns.name AS ColumnName,
    sys.types.name AS TypeName,
    sys.columns.precision AS NumericPrecision,
    sys.columns.scale AS NumericScale,
    sys.columns.is_nullable AS IsNullable,
    (   SELECT 
            COUNT(column_name)
        FROM 
            INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE 
        WHERE
            TABLE_NAME = sys.tables.name AND
            CONSTRAINT_NAME =
                (   SELECT
                    constraint_name
                    FROM 
                        INFORMATION_SCHEMA.TABLE_CONSTRAINTS
                    WHERE
                        TABLE_NAME = sys.tables.name AND                    
                        constraint_type = 'PRIMARY KEY' AND
                        COLUMN_NAME = sys.columns.name
                )
    ) AS IsPrimaryKey,
    sys.columns.max_length / 2 AS CharMaxLength /*BUG*/
FROM 
    sys.columns, sys.types, sys.tables 
WHERE
    sys.tables.object_id = sys.columns.object_id AND
    sys.types.system_type_id = sys.columns.system_type_id AND
    sys.types.user_type_id = sys.columns.user_type_id AND
    sys.tables.name = 'TABLE'
ORDER BY 
    IsPrimaryKey

You can use only the primary key part, but I think that the rest might become handy. Best regards, David

David Conde
+1  A: 

I also found another one for SQL Server:

SELECT column_name
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1
AND table_name = 'TableName'
Awan
SImplexst solution. Astonisching now many people here seem to not have read the documentation for 10 years and still do not know about INFORMATION_SCHEMA.
TomTom
It is not running on SQL Server 2005. I added another answer which is useful for both SQL Server 2003 and SQL Server 2005.
Awan
+1  A: 

It is also (Transact-SQL) ... according to BOL.

-- exec sp_serveroption 'SERVER NAME', 'data access', 'true' --execute once  

EXEC sp_primarykeys @table_server = N'server_name', 
  @table_name = N'table_name',
  @table_catalog = N'db_name', 
  @table_schema = N'schema_name'; --frequently 'dbo'
vgv8
A: 

Found another one:

SELECT KU.table_name as tablename,column_name as primarykeycolumn
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC
INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU
ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND
TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME
and ku.table_name='yourTableName'
ORDER BY KU.TABLE_NAME, KU.ORDINAL_POSITION;

I have tested this on SQL Server 2003/2005

Awan