SQL SERVER – 2005 – List All The Constraint of Database – Find Primary Key and Foreign Key Constraint in Database

Following script are very useful to know all the constraint in the database. I use this many times to check the foreign key and primary key constraint in database. This is simple but useful script from my personal archive.
USE AdventureWorks;
GO
SELECT OBJECT_NAME(OBJECT_ID) AS NameofConstraint,
SCHEMA_NAME(schema_id) AS SchemaName,
OBJECT_NAME(parent_object_id) AS TableName,
type_desc AS ConstraintType
FROM sys.objects
WHERE type_desc LIKE '%CONSTRAINT'
GO

Reference : Pinal Dave (https://blog.sqlauthority.com)

SQL Constraint and Keys, SQL Scripts, SQL System Table
Previous Post
SQLAuthority News – Random Article from SQLAuthority Blog
Next Post
SQLAuthority News – Active Directory Integration Sample Script

Related Posts

101 Comments. Leave new

  • Hello Sir,

    The query to get all Database level constraints is :

    SELECT OBJECT_NAME(OBJECT_ID) AS NameofConstraint,
    SCHEMA_NAME(schema_id) AS SchemaName,
    OBJECT_NAME(parent_object_id) AS TableName,
    type_desc AS ConstraintType
    FROM sys.objects
    WHERE type_desc LIKE ‘%CONSTRAINT’

    which u have already given……….

    But my issue is
    I am having 100 databases so for that i have to run the above query in all databases one by one…….
    i tried sp_msforeachdb but not working…….

    You have any query which will give me the above details for all Datbases in one shot…

    Reply
    • Try this code

      sp_msforeachdb ‘
      SELECT OBJECT_NAME(OBJECT_ID) AS NameofConstraint,
      SCHEMA_NAME(schema_id) AS SchemaName,
      OBJECT_NAME(parent_object_id) AS TableName,
      type_desc AS ConstraintType
      FROM ?.sys.objects
      WHERE type_desc LIKE ”%CONSTRAINT”’

      Reply
    • If you want to include database name too, use this

      sp_msforeachdb ‘
      SELECT ”?”,OBJECT_NAME(OBJECT_ID) AS NameofConstraint,
      SCHEMA_NAME(schema_id) AS SchemaName,
      OBJECT_NAME(parent_object_id) AS TableName,
      type_desc AS ConstraintType
      FROM ?.sys.objects
      WHERE type_desc LIKE ”%CONSTRAINT”’

      Reply
  • if msforeachdb not working then try with cursor…
    just giving you an example, which will go in each database and will print the database name using cursor. you can modify it as per your requirement :-

    declare @name varchar(200)
    declare c1 cursor for
    select name from master..sysdatabases
    open c1
    FETCH NEXT FROM c1 into @name
    WHILE @@FETCH_STATUS = 0
    begin
    print @name + ‘ is database name’
    FETCH NEXT FROM c1 into @name
    end
    close c1
    deallocate c1

    Reply
  • Hi Pinal,
    Generally I get any new comments addedd on this website to my mail id. But since last 2 days I am no more getting it.
    Is there anything changed on this blog?

    Reply
  • مجتبی ولی
    August 26, 2010 1:22 pm

    I think it is better when we change the condition

    SELECT *, OBJECT_NAME(OBJECT_ID) AS ConstraintName,SCHEMA_NAME(schema_id) AS SchemaName,OBJECT_NAME(parent_object_id) AS TableName,type_desc AS ConstraintType FROM sys.objects WHERE (OBJECTPROPERTY(object_Id, N’IsConstraint’) = 1)

    i don’t know if we gain a performance boost or not but it looks more reliable to me

    Reply
  • @abhay
    Really helpfull….Thanks

    Reply
  • While I was working in SQL server 2005, I used to know domain constraint have higher priority than referential constraint. Now I am little bit confusion regarding the priority among constraints in sql server. I will be thankful if u give a brief discussion regarding priority among constraints.

    Reply
  • Vishwas Khanal
    March 25, 2011 12:22 pm

    Does any one have an idea about how to get the violated constrained name.

    eg If I get an error Violation of PRIMARY KEY constraint ‘pk24’. Cannot insert duplicate key in object ‘xyz’.
    I would like to catch pk24 alone.

    Is there a way out?

    Reply
    • exec sp_pkeys xyz

      Reply
      • Vishwas Khanal
        April 5, 2011 4:40 pm

        madhivanan,

        ERROR_NUMBER() – catches error no,
        ERROR_MESSAGE() – catches error msg,
        ERROR_PROCEDURE() – catches procedure name ,
        ERROR_LINE() – catches line no

        How do i catch the constraint name if the error is about the violation of primary key?

      • You need to parse the error_message() and get that between contraint and cannot

  • hi sir,
    explain about constraints and uses of constraints

    Reply
  • Sir,
    The query of Default Constraint which u have given,i executed that but at d time of inserting d records in d table d is error has occured.
    The default value which is hav to go automatically in the table that has not done.
    Plz send me d feedback that how to do that.
    Thanks.

    Reply
  • hello sir i need ur help …

    Reply
  • would u ple send me sql information

    Reply
  • Alderi Pereira
    May 19, 2011 6:42 pm

    if object_id(‘tempdb..#tmp’) is not null
    drop table #tmp

    select
    ‘[‘ + SCHEMA_NAME(o1.schema_id) + ‘].[‘ + o1.name + ‘]’ as Referencing_Object_name
    , s.name as Constraint_name
    , c1.name as referencing_column_Name
    , ‘[‘ + SCHEMA_NAME(o2.schema_id) + ‘].[‘ + o2.name + ‘]’ as Referenced_Object_name
    , c2.name as Referenced_Column_Name
    , fk.keyno as orderKey
    , ‘[‘ + SCHEMA_NAME(o1.schema_id) + ‘].[‘ + s.name + ‘]’ Constraint_name_schema
    into #tmp
    from sysforeignkeys fk
    inner join sys.objects o1 on fk.fkeyid = o1.object_id
    inner join sys.objects o2 on fk.rkeyid = o2.object_id
    inner join sys.columns c1 on c1.object_id = o1.object_id and c1.column_id = fk.fkey
    inner join sys.columns c2 on c2.object_id = o2.object_id and c2.column_id = fk.rkey
    inner join sys.objects s on fk.constid = s.object_id
    and o2.name='<>’ — this predicate for a specific table
    order by 1, fk.keyno

    select distinct
    ‘IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N”’+ Constraint_name_schema + ”’) AND parent_object_id = OBJECT_ID(N”’ + Referencing_Object_name + ”’))’ + char(13) + char(10) + char(9) +
    ‘ALTER TABLE ‘ +
    Referencing_Object_name +
    ‘ DROP CONSTRAINT ‘ +
    Constraint_name
    from #tmp o1

    select distinct
    ‘ALTER TABLE ‘ +
    Referencing_Object_name +
    ‘ WITH NOCHECK ADD CONSTRAINT ‘ +
    Constraint_name +
    ‘ FOREIGN KEY ‘ +
    ‘(‘ +
    STUFF(( SELECT
    ‘],[‘ + c1.referencing_column_Name
    FROM #tmp c1
    where c1.Referencing_Object_name = o1.Referencing_Object_name
    group by c1.referencing_column_Name,orderKey
    order by orderKey
    FOR XML PATH(”)
    ), 1, 2, ”) + ‘]’
    + ‘)’ + char(13) + char(10) + char(9) +
    ‘ REFERENCES ‘ +
    Referenced_Object_name +
    ‘(‘ +
    STUFF(( SELECT
    ‘],[‘ + c1.Referenced_Column_Name
    FROM #tmp c1
    where c1.Referenced_Object_name = o1.Referenced_Object_name
    group by c1.Referenced_Column_Name,orderKey
    order by orderKey
    FOR XML PATH(”)
    ), 1, 2, ”) + ‘]’
    + ‘)’
    from #tmp o1

    Reply
  • does anybody know how to list the column names which are included in the check constraint

    Reply
    • Look at these views

      select * from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE
      select * from INFORMATION_SCHEMA.CHECK_CONSTRAINTS

      Reply
  • Hello,

    Is there any way to get the data in one table is referencing in any other tables

    For eg: I have 3 tables say tbl1,tbl2,tbl3.

    tbl1 contains 3 records say 1,2,3

    But only 1 and 2 are referencing tbl2 and tbl3,

    If we delete the record 1 or 2 from tbl1 ,it is not possible.since the data is using in tbl2 or tbl3.

    But if delete 3 from tbl1 it is possible.

    So my question is, the way to find out whether the data is referencing in some other places without writing the delete query.

    Through proc I pass the values 1,2,3 etc.

    Thanks.
    Manoj

    Reply
    • Use join or exists

      select * from table as t exists(select * from othertable ot where t.id=ot.id)

      Reply
  • I think it will not solve my problem.

    The following query returns all related tables for tbl1.

    select
    o1.name as Referencing_Object_name
    , c1.name as referencing_column_Name
    , o2.name as Referenced_Object_name
    , c2.name as Referenced_Column_Name
    , s.name as Constraint_name
    from sysforeignkeys fk
    inner join sysobjects o1 on fk.fkeyid = o1.id
    inner join sysobjects o2 on fk.rkeyid = o2.id
    inner join syscolumns c1 on c1.id = o1.id and c1.colid = fk.fkey
    inner join syscolumns c2 on c2.id = o2.id and c2.colid = fk.rkey
    inner join sysobjects s on fk.constid = s.id
    and o2.name=’tbl1′ and c2.name=’ID’

    I also need to get is there any data in the referenced tables.

    We can do this by writing a dynamic query by checking count in each table.

    Other than this i am looking for a simplest way.

    When we delete a record from the main table, and it has some references,we usually get the below error msg.

    The DELETE statement conflicted with the REFERENCE constraint “FK_tbl3_tbl1″. The conflict occurred in database ” db1 “, table “dbo.tbl3”, column ‘ID’.
    The statement has been terminated.

    So definitely SQL Server should have some system procedures, that is checking this dependencies(means existence of records in related tables).

    What is that sp..?

    Thanks

    Reply
  • how to find out not null constraints columns in a table using sql command

    Reply
  • Anyone know if there is any way to get the constaintas tha are defined as “with check add”?

    Reply
  • Sir, if i ve given name to some constraints such as pk1 etc and at last if i want to know the constraint names that i ve assigned then hw can i see using select statements? Plz reply

    Reply
    • A common scenario is where one needs write a schema change script to drop a column from a table, but first a constraint that references the column must be dropped. If the constraint has a name that was auto generated (ex: DF__MyTable_MyColumn__26E730D3), then that’s problematic, because the name may be different across dev, qa, prod, etc. So, here is an example for dynamically determining the name of constraint and then dropping it.

      declare @myconstraint varchar(8000);
      select @myconstraint = name
      from sys.default_constraints
      where object_name(parent_object_id) = ‘mytable’
      and col_name (parent_object_id, parent_column_id) = ‘mycolumn’;
      if @myconstraint is not null
      exec(‘alter table mytable drop constraint ‘+@myconstraint);

      Reply
  • Raja Jeevan Kumar Maduri
    November 15, 2011 4:35 pm

    Folks,

    I would want to run a query against a database where in I wanted to specify a column/field, which has been referenced in multiple DB tables. And the result of the query should retrieve me information about the field’s reference in a particular DB table and the column name being referenced along with the field description/documentation, if any. I am not a developer or a DBA. But, I just need this information for documentation. Thanks a ton before hand for responding back to my query.

    Reply
  • I am new to sql…given this job in our company because another person quit.
    weeeeeee LOL

    SQL SERVER 2008 R2
    anyway I have to merge 2 databases (finally got it done) one has more columns and tables than the other so I had a heck of a time.

    Now they have a 3rd production database they want to remove all data and put the merged data into it.
    So I get a copy of the production one and remove all data

    MAKE SURE to PRESERVE THE SCHEMA so we an just take this one and put it into production.

    HUH???

    anyway I remove all data and start importing. Tough to put a real into an int.
    Ok I change the int into a real on import of the table

    later its datetimes into short dates ETC this is a nightmare
    then I look and all the primary keys and foreign keys (IN view) no longer show they are linked.

    ENOUGH whining, my question.

    I have the original PRODUCTION DATABASE and I am working in a copy.

    HOW do I get the pk and fk information from the original database and put it in the copy to restore all the keys and links like the production one?

    one person I talked to said just backup script on the original.
    ok then what…oh I don’t know just put it in the copy.
    then what
    NO MORE IDEAS I am lost

    Reply

Leave a Reply