Monday, March 12, 2012

Primary Information

Given a column id/name and table name/id I need to find out if the
column is a primary key. I have checked all the SYS* tables and could
not find the information I was after. Can you point me in the right
direction please. Thanks.Sadly, this is not one of the options in the COLUMNPROPERTY() function. You
could write your own function or procedure that does this:
IF EXISTS
(
SELECT
1
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS T
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE K
ON T.CONSTRAINT_NAME = K.CONSTRAINT_NAME
WHERE
T.CONSTRAINT_TYPE = 'PRIMARY KEY'
AND T.TABLE_NAME = 'table_name'
AND K.COLUMN_NAME = 'column_name'
)
PRINT 'Column is a primary key';
ELSE
PRINT 'Column is not a primary key';
"S Chapman" <s_chapman47@.hotmail.co.uk> wrote in message
news:1149869140.156553.134430@.i40g2000cwc.googlegroups.com...
> Given a column id/name and table name/id I need to find out if the
> column is a primary key. I have checked all the SYS* tables and could
> not find the information I was after. Can you point me in the right
> direction please. Thanks.
>|||Thank you very much. INFORMATION_SCHEMA is an eye-opener.
Aaron Bertrand [SQL Server MVP] wrote:
> Sadly, this is not one of the options in the COLUMNPROPERTY() function. Y
ou
> could write your own function or procedure that does this:
> IF EXISTS
> (
> SELECT
> 1
> FROM
> INFORMATION_SCHEMA.TABLE_CONSTRAINTS T
> INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE K
> ON T.CONSTRAINT_NAME = K.CONSTRAINT_NAME
> WHERE
> T.CONSTRAINT_TYPE = 'PRIMARY KEY'
> AND T.TABLE_NAME = 'table_name'
> AND K.COLUMN_NAME = 'column_name'
> )
> PRINT 'Column is a primary key';
> ELSE
> PRINT 'Column is not a primary key';
>
> "S Chapman" <s_chapman47@.hotmail.co.uk> wrote in message
> news:1149869140.156553.134430@.i40g2000cwc.googlegroups.com...

No comments:

Post a Comment