Click here to Skip to main content
15,896,201 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
How to  find constraints for tables with identity insert for a database in Sql server?


I am able to get the Tables with Identity Insert wit
SQL
How to  list the  constraints for all tables with identity insert of a database in SQL server?h below query
<pre lang="SQL">       select TABLE_NAME
       from INFORMATION_SCHEMA.COLUMNS
       where TABLE_SCHEMA = 'dbo'
      and 
COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
      ORDER BY ORDINAL_POSITION</pre>

I need to fetch the constraints of the tables  with identity insert column alone.
I am able to fetch all constraints for a DB with below query. but it's needed for tables with identity insert alone
<pre lang="SQL">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 &#39;%CONSTRAINT&#39;</pre>


What I have tried:

select TABLE_NAME
from INFORMATION_SCHEMA.COLUMNS
where TABLE_SCHEMA = 'dbo'
and
COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
ORDER BY ORDINAL_POSITION

I am able to fetch all constraints for a DB with below query. but it's needed for tables with identity insert alone
SQL
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'
Posted
Updated 5-Apr-16 3:01am
v2

1 solution

You can do another (self) join to the sys.objects table to restrict the tables e.g.
SELECT TABS.name, CONS.name, CONS.type_desc
FROM sys.objects TABS
JOIN sys.columns COLS ON TABS.object_id = COLS.object_id
JOIN sys.objects CONS ON TABS.object_id = CONS.parent_object_id AND CONS.type_desc LIKE '%CONSTRAINT'
WHERE TABS.type_desc='USER_TABLE'
AND SCHEMA_NAME(TABS.schema_id) = 'dbo'
AND COLS.is_identity = 1
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900