当前位置:   article > 正文

sql server删除外键_sqlserver删除外键

sqlserver删除外键
  1. -- 查询指定数据库外键
  2. SELECT
  3. fk.name AS '外键名称',
  4. tp.name AS '表名',
  5. ref.name AS '参考表',
  6. col.name AS '列名'
  7. FROM
  8. sys.foreign_keys AS fk
  9. INNER JOIN sys.tables AS tp ON fk.parent_object_id = tp.object_id
  10. INNER JOIN sys.tables AS ref ON fk.referenced_object_id = ref.object_id
  11. INNER JOIN sys.foreign_key_columns AS fkc ON fkc.constraint_object_id = fk.object_id
  12. INNER JOIN sys.columns AS col ON fkc.parent_column_id = col.column_id AND fkc.parent_object_id = col.object_id
  13. WHERE DB_NAME() = 'Plan';
  14. -- 删除单个外键
  15. ALTER TABLE PLR_GraphicProgressAttached DROP CONSTRAINT RefPL_GraphicProgress232;
  16. -- 删除指定库所有外键
  17. DECLARE @SqlStatement NVARCHAR(MAX);
  18. SET @SqlStatement = (
  19. SELECT STUFF((
  20. SELECT '; ALTER TABLE ' + tp.name + ' DROP CONSTRAINT ' + fk.name
  21. FROM sys.foreign_keys AS fk
  22. INNER JOIN sys.tables AS tp ON fk.parent_object_id = tp.object_id
  23. INNER JOIN sys.tables AS ref ON fk.referenced_object_id = ref.object_id
  24. INNER JOIN sys.foreign_key_columns AS fkc ON fkc.constraint_object_id = fk.object_id
  25. INNER JOIN sys.columns AS col ON fkc.parent_column_id = col.column_id AND fkc.parent_object_id = col.object_id
  26. WHERE DB_NAME() = 'Plan'
  27. FOR XML PATH('')
  28. ), 1, 1, '')
  29. );
  30. EXEC sp_executesql @SqlStatement;

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/497448
推荐阅读
相关标签
  

闽ICP备14008679号