Posts Tagged ‘SYSTEM TABLES’
Generating Alter Query on the basis of the foreign keys present in the database
We can utilize the query of listing foreign key with respective table and fields to generate the alter query for adding constraint. For that we will use the XML and temp table and will generate the list of the alter queries
SELECT TABS.NAME AS [REFTABLE], (SELECT NAME FROM SYS.TABLES AS CTAB WHERE (OBJECT_ID = FK.PARENT_OBJECT_ID)) AS [PARENTTABLE], FK.NAME AS [KEYNAME], AC.NAME AS [COLUMNNAME] INTO #TEMPTABLE FROM SYS.TABLES AS TABS INNER JOIN SYS.FOREIGN_KEYS AS FK ON FK.REFERENCED_OBJECT_ID = TABS.OBJECT_ID INNER JOIN SYS.FOREIGN_KEY_COLUMNS AS FKC ON FK.OBJECT_ID = FKC.CONSTRAINT_OBJECT_ID INNER JOIN SYS.ALL_COLUMNS AS AC ON AC.COLUMN_ID = FKC.PARENT_COLUMN_ID AND AC.OBJECT_ID = FKC.PARENT_OBJECT_ID SELECT 'ALTER TABLE ' + [PARENTTABLE] + ' ADD CONSTRAINT ' + [KEYNAME] + ' FOREIGN KEY (' + REPLACE((SELECT [COLUMNNAME] AS 'data()' FROM #TEMPTABLE AS TT WHERE TT.[KEYNAME] = #TEMPTABLE.[KEYNAME] FOR XML PATH('')),' ',',') + ') REFERENCES (' + REPLACE((SELECT [COLUMNNAME] AS 'data()' FROM #TEMPTABLE AS TT WHERE TT.[KEYNAME] = #TEMPTABLE.[KEYNAME] FOR XML PATH('')),' ',',') + ') ON UPDATE CASCADE ON DELETE CASCADE' FROM #TEMPTABLE GROUP BY [KEYNAME], [PARENTTABLE], [REFTABLE] DROP TABLE #TEMPTABLE
Getting List of all the foreign keys and there details with table and field name
To list the all the foreign keys available in database and there associated tables and fields we can utilize following query
SELECT tabs.name AS [Reference Table], (SELECT name FROM sys.tables AS ctab WHERE (object_id = fk.parent_object_id)) AS [Parent Table], fk.name AS [Key Name], ac.name AS [Column Name] FROM sys.tables AS tabs INNER JOIN sys.foreign_keys AS fk ON fk.referenced_object_id = tabs.object_id inner join sys.foreign_key_columns as fkc on fk.object_id = fkc.constraint_object_id inner join sys.all_columns as ac on ac.column_id = fkc.parent_column_id and ac.object_id = fkc.parent_object_id ORDER BY tabs.name, 2