how get primary key in any database

  • Comments posted to this topic are about the item how get primary key in any database

  • This information can be gotten despite how the constraint is named this way:

    SELECT Table_name, constraint_name

    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS

    WHERE constraint_type = 'PRIMARY KEY'

    then you can use the table_name and constraint_name to do what you wish.

    Toni

  • To be clearer, as you can name the primary key anything you want the statements from the article would miss any that do not begin with 'PK'.

    declare @name_pk varchar(255)

    select @name_pk = name from sysindexes where id in (select id from sysobjects where name = 'table_name') and name like 'PK%'

    execute ('alter table table_name drop constraint ' + @name_pk)

    So to get the name of the Primary Key Constraint without this restriction, using the same 'table_name' substitution:

    declare @name_pk varchar(255)

    SELECT @name_pk = constraint_name

    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS

    WHERE constraint_type = 'PRIMARY KEY' and Table_name = 'table_name'

    Print 'pk ' + @name_pk -- show the results

    /* or use the execute as in the original */

    -- execute ('alter table table_name drop constraint ' + @name_pk)

    Toni

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply