Script all Foreign Key Constraints - Result Set can be used to DROP constraints for 'TableName'


/ 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. ' drop CONSTRAINT '+C.CONSTRAINT_NAME AS ForeignKeyScripts
  6. FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
  7. INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
  8. INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
  9. INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
  10. INNER JOIN (
  11. SELECT i1.TABLE_NAME, i2.COLUMN_NAME
  12. FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
  13. INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
  14. WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
  15. ) PT ON PT.TABLE_NAME = PK.TABLE_NAME
  16. AND PK.TABLE_NAME = 'TableName'

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.