Script all Foreign Key Constraints - Result Set can be used to copy constraints to your testing DB or to keep on hand in case of


/ Published in: SQL
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /*** Script all Foreign Key Constraints ***/
  2. /*** The Result Set can be used to copy constraints to your testing DB or to keep on hand in case of errors. ***/
  3. SELECT
  4. 'ALTER TABLE '+FK.TABLE_NAME+
  5. ' ADD CONSTRAINT '+C.CONSTRAINT_NAME+' FOREIGN KEY'+
  6. '('+CU.COLUMN_NAME+') '+
  7. 'REFERENCES '+PK.TABLE_NAME+
  8. '('+PT.COLUMN_NAME+')' ForeignKeyScripts
  9. FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
  10. INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
  11. INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
  12. INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
  13. INNER JOIN (
  14. SELECT i1.TABLE_NAME, i2.COLUMN_NAME
  15. FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
  16. INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
  17. WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
  18. ) PT ON PT.TABLE_NAME = PK.TABLE_NAME

URL: http://blog.sqlauthority.com/2007/09/04/sql-server-2005-find-tables-with-foreign-key-constraint-in-database/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.