Tuesday, 15 August 2017

Get the list of all Constraint in all the databases in SQL Server

With the help of below sql script we will get the list of all constraint in all databases in sql server.
DECLARE @DDL VARCHAR(MAX)
SET @DDL='SELECT CONSTRAINT_NAME,
                CONSTRAINT_CATALOG as Database_Name,
                 TABLE_SCHEMA ,
     TABLE_NAME,
     CONSTRAINT_TYPE
     FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS'
Create table #temp
(CONSTRAINT_NAME Varchar(100),
 Database_Name Varchar(100),
 TABLE_SCHEMA Varchar(100),
 TABLE_NAME Varchar(100),
 CONSTRAINT_TYPE Varchar(500)
 )

DECLARE @DatabaseName AS VARCHAR(500)
--DECLARE CURSOR
DECLARE CUR CURSOR FOR
--Choose the DBs on which we would like to run the script
SELECT NAME
FROM sys.databases
WHERE database_id > 4
--OPEN CURSOR
OPEN CUR
--NEXT NEXT RECORD
FETCH NEXT FROM CUR
INTO @DatabaseName
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @DBName AS NVARCHAR(500);
SET @DBName = QUOTENAME(N'' + @DatabaseName + '');

Insert into #temp
EXEC ( N'USE ' + @DBName + N'; EXEC('''+@DDL+''');' );
 print @DBName + '  '+ @DDL
FETCH NEXT
FROM CUR
INTO @DatabaseName
END
CLOSE CUR
DEALLOCATE CUR
Select * from #temp
DROP table #temp
See the output.



No comments:

Post a Comment

If you have any doubt, please let me know.

Popular Posts