Monday, 2 June 2014

How to find KeyConstraint Columns on Table in SQL Server

Find PrimaryKey Columns on Table

 here i want to know the Column Name on which the key constraints are created.
Initially i was concentrated on Primary Key constraints.
Here i am displaying Constraint Name ,Tablename ,ColumnName

SELECT i.name                               AS IndexName,
       Object_name(ic.object_id)            AS TableName,
       Col_name(ic.object_id, ic.column_id) AS ColumnName
FROM   sys.indexes AS i
       INNER JOIN sys.index_columns AS ic
               ON i.object_id = ic.object_id
                  AND i.index_id = ic.index_id
WHERE  i.is_primary_key = 1


SELECT i.name                               AS IndexName,
       Object_name(ic.object_id)            AS TableName,
       Col_name(ic.object_id, ic.column_id) AS ColumnName
FROM   sys.indexes AS i
       INNER JOIN sys.index_columns AS ic
               ON i.object_id = ic.object_id
                  AND i.index_id = ic.index_id

If you want the table name only, use the CTE & to know the primarykey of a specific table you can filter it with table name
with cte as(
SELECT i.name AS IndexName,
        OBJECT_NAME(ic.OBJECT_ID) AS TableName,
        COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName
FROM    sys.indexes AS i INNER JOIN  sys.index_columns AS ic ON  i.OBJECT_ID = ic.OBJECT_ID
                                AND i.index_id = ic.index_id
WHERE   i.is_primary_key = 1
)select *  from cte
--where TableName='Document'

5 comments:

  1. Je vais finir de voir ça ce soir

    My site; chaude du cul x

    ReplyDelete
  2. Une fߋis de plus un superbe poѕte, j'en paгlerai ce soir aѵec Ԁes
    amis

    Feеel frеe too suref to my webb bloց porn traînée
    - www.123-you.nu,

    ReplyDelete
  3. Un аrtiϲle rempli de vérіtés

    Alsο visit my web-site http://www.cupcakes-maken.nu

    ReplyDelete
  4. Un ɑrticle plein de bon sens

    Also visit my web page ... pause porno

    ReplyDelete
  5. Je prends la peine de publier ce commentaire simplement
    pour complimenter son auteur

    my site ... grosse

    ReplyDelete

EMP, DEPT Sample script

/****** Object:  Table [dbo].[DEPT]    Script Date: 19-05-2016 06:58:37 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET A...