I need a primary key name and primary key column name of a table please tell me what query should I write..
A:
Not quite what you're looking for, but you can play around with it:
SQL 2000: T-SQL to get foreign key relationships for a table
Randolph Potter
2010-01-07 07:50:10
+2
A:
declare @tableName as nvarchar(100)
set @tableName = 'table'
select i.name, c.name
from sys.index_columns ic
join sys.indexes i on ic.index_id=i.index_id
join sys.columns c on c.column_id=ic.column_id
where
i.[object_id] = object_id(@tableName) and
ic.[object_id] = object_id(@tableName) and
c.[object_id] = object_id(@tableName) and
is_primary_key = 1
Jonas Lincoln
2010-01-07 08:09:43
Why only 100? Sysname can be 128.
CodeByMoonlight
2010-01-07 09:11:55
No reason, really. I just used an even number.
Jonas Lincoln
2010-01-07 09:24:09
@Jonas: 128 is even, too :-)
marc_s
2010-01-07 09:58:26
Haha, that's true :)
Jonas Lincoln
2010-01-07 10:26:52
+1
A:
Here's another option that uses the INFORMATION_SCHEMA views
SELECT
cu.Table_Catalog,
cu.Table_Schema,
cu.table_name,
cu.Constraint_name ,
cu.column_name
FROM
sys.indexes si
inner join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE cu
on si.name = cu.constraint_name
WHERE
is_primary_key = 1
Conrad Frix
2010-01-07 16:42:17
+1 This is preferable to the database-specific sys tables. (@soslo: how slow can it be??? :)
Todd Owen
2010-07-09 11:57:02
A:
Just a performance note - the select using sys tables is a couple orders of magnitude faster than the select that uses INFORMATION_SCHEMA views
soslo
2010-07-08 17:50:25