Search code examples
sybasesap-ase

how to identify in a query whether the table has a Primary key or not


Is it possible to write a query that determines if the table has a primary key or not?

SELECT * FROM sysobjects WHERE id = OBJECT_ID('TRS') and xtype = PK

If it doesn't have primary then it will return nothing.

In this link the author said about using Xtype but it seems it's an old term.


Solution

  • This will give you the key and it's column name if there is a primary key, else nothing.

    SELECT sysobjects.name, syscolumns.name
    FROM
      sysobjects INNER JOIN 
      syscolumns ON syscolumns.id = sysobjects.id INNER JOIN
      syskeys ON syskeys.id = sysobjects.id
    WHERE 
      sysobjects.type = 'U' AND syskeys.type = 1