如何删除并重新创建主键和外键

时间:2014-02-19 05:36:59

标签: sql-server

我有一个包含主键和外键列表的数据库。我想删除所有外键和主键,并重新创建两个键。截至目前,我已经能够删除并重新创建主键但无法在删除后添加外键。我没有在掉线后重新创建所有外键。

- 使用drop语句获取所有外键的查询

SELECT    'IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''' + QUOTENAME(SCHEMA_NAME()) + '.' + QUOTENAME(fk.name) + ''') AND parent_object_id = OBJECT_ID(N''' + QUOTENAME(SCHEMA_NAME()) + '.' + QUOTENAME(so.name) + '''))' + CHAR(13)
        + 'ALTER TABLE ' + QUOTENAME(SCHEMA_NAME()) + '.' + QUOTENAME(so.name) + ' DROP CONSTRAINT ' + QUOTENAME(fk.name) + '' 
FROM    sys.foreign_keys fk
        inner join sys.sysobjects so ON (fk.parent_object_id = so.id)

- 使用Add语句获取所有外键的查询

SELECT    'ALTER TABLE ' + QUOTENAME(SCHEMA_NAME()) + '.' + QUOTENAME(spo.Name) + ' WITH CHECK ADD CONSTRAINT ' + QUOTENAME(fk.name) + ' FOREIGN KEY(' + QUOTENAME(fkpc.name) + ') REFERENCES ' + QUOTENAME(SCHEMA_NAME()) + '.' + QUOTENAME(sro.name) + ' (' + QUOTENAME(fkrc.name) + ')' + CHAR(13)
        + 'ALTER TABLE ' + QUOTENAME(SCHEMA_NAME()) + '.' + QUOTENAME(spo.name) + ' CHECK CONSTRAINT ' + QUOTENAME(fk.name) + '' + CHAR(13) + CHAR(13)
FROM    sys.foreign_keys fk
        INNER JOIN sys.sysobjects spo on (fk.parent_object_id = spo.id)
        INNER JOIN sys.sysobjects sro on (fk.referenced_object_id = sro.id)
        INNER JOIN sys.foreign_key_columns fkc on (fk.object_id = fkc.constraint_object_id)
        INNER JOIN sys.all_columns fkpc on (fkc.parent_object_id = fkpc.object_id and fkc.parent_column_id = fkpc.column_id)
        INNER JOIN sys.all_columns fkrc on (fkc.referenced_object_id = fkrc.object_id and fkc.referenced_column_id = fkrc.column_id)   

1 个答案:

答案 0 :(得分:0)

要删除所有外键,您可以尝试使用此脚本:

while(exists(select 1 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE='FOREIGN KEY'))
begin
 declare @constraints nvarchar(2000)
 SELECT TOP 1 @constraints=('ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + '] DROP CONSTRAINT [' + CONSTRAINT_NAME + ']')
 FROM information_schema.table_constraints
 WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'
 exec (@constraints)
 PRINT @constraints
end
GO

不要忘记在您的数据库上运行它! ))