sqlServer从一个数据库导数到另一个库的时候,如果目标库有外键约束,可能会导致导数失败。这时,可以将外键先删除或禁用,等导数完成后再重建或启用外键。
禁用、启用外键:
[sql] view plain copy
DECLARE @nochecksql NVARCHAR(max)--禁用外键约束的sql SET @nochecksql = (SELECT 'alter table dbo.['+b.name+'] nocheck constraint ['+a.name+'];' from sysobjects a,sysobjects b where a.xtype='f' and a.parent_obj=b.ID and b.xtype='u' for xml PATH('') ) print @nochecksql --execute sp_executesql @nochecksql DECLARE @checksql NVARCHAR(max)--启用外键约束的sql SET @checksql = (SELECT 'alter table dbo.['+b.name+'] check constraint ['+a.name+'];' from sysobjects a,sysobjects b where a.xtype='f' and a.parent_obj=b.ID and b.xtype='u' for xml PATH('') ) print @checksql --execute sp_executesql @checksql删除、重建外键:
[sql] view plain copy
declare @createsql nvarchar(max) declare @delsql nvarchar(max) Set @createsql = ( select 'ALTER table ['+OBJECT_name(k.parent_object_ID)+'] ADD CONSTRAINT ['+k.name+'] FOREIGN KEY (['+Col_name(k.parent_object_ID,c.parent_column_ID)+']) REFERENCES ['+OBJECT_name(k.referenced_object_ID)+'](['+Col_name(k.referenced_object_ID,key_index_ID)+'])'+case k.delete_referential_action when 0 then '' when 1 then ' ON DELETE CASCADE ' when 2 then ' ON DELETE SET NulL ' when 3 then ' ON DELETE SET DEFAulT ' END+ case k.update_referential_action when 0 then '' when 1 then ' ON UPDATE CASCADE ' when 2 then ' ON UPDATE SET NulL ' when 3 then ' ON UPDATE SET DEFAulT' end +';' from sys.foreign_keys k,sys.foreign_key_columns c where c.constraint_object_ID=k.object_ID for xml path('') ) print @createsql--重建外键约束的语句 set @delsql = ( select 'alter table ['+O.name+'] drop constraint ['+F.name+'];' from sysobjects O,sys.foreign_keys F where F.parent_object_ID=O.ID for xml path('') ) print @delsql --删除外键约束的语句 --exec sp_executesql @delsql --exec sp_executesql @createsql 总结以上是内存溢出为你收集整理的SQLServer删除/重建/禁用/启用外键约束全部内容,希望文章能够帮你解决SQLServer删除/重建/禁用/启用外键约束所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)