Friday, July 30, 2010

Query to get PrimaryKey, ForeignKey, IdentityKey, UniqueKey column names

DECLARE  @TableName NVARCHAR(50)
SET @TableName = 'PkFkIkTestIdentAsPk'
 
 SELECT
  C.COLUMN_NAME,
  C.DATA_TYPE,
  C.ORDINAL_POSITION 
 FROM
  INFORMATION_SCHEMA.COLUMNS C 
  LEFT JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS COL
  ON col.TABLE_NAME = C.TABLE_NAME 
  AND col.COLUMN_NAME = C.COLUMN_NAME
  INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tblCons 
 ON tblCons.CONSTRAINT_NAME = col.CONSTRAINT_NAME 
 WHERE tblCons.TABLE_NAME = @TableName 
  AND 
  (
   tblCons.CONSTRAINT_TYPE = 'PRIMARY KEY' 
  OR tblCons.CONSTRAINT_TYPE = 'FOREIGN KEY' 
  OR tblCons.CONSTRAINT_TYPE = 'UNIQUE' 
  )
 UNION 
  SELECT C.COLUMN_NAME,
  C.DATA_TYPE,
  C.ORDINAL_POSITION
  FROM
  INFORMATION_SCHEMA.COLUMNS C
  WHERE C.TABLE_NAME = @TableName
  AND COLUMNPROPERTY(OBJECT_ID(C.TABLE_NAME), C.COLUMN_NAME,'IsIdentity') = 1

No comments: